LeetCode 925. 長按鍵入(C、C++、python)
阿新 • • 發佈:2018-12-17
你的朋友正在使用鍵盤輸入他的名字 name
。偶爾,在鍵入字元 c
時,按鍵可能會被長按,而字元可能被輸入 1 次或多次。
你將會檢查鍵盤輸入的字元 typed
。如果它對應的可能是你的朋友的名字(其中一些字元可能被長按),那麼就返回 True
。
示例 1:
輸入:name = "alex", typed = "aaleex" 輸出:true 解釋:'alex' 中的 'a' 和 'e' 被長按。
示例 2:
輸入:name = "saeed", typed = "ssaaedd" 輸出:false 解釋:'e' 一定需要被鍵入兩次,但在 typed 的輸出中不是這樣。
示例 3:
輸入:name = "leelee", typed = "lleeelee" 輸出:true
示例 4:
輸入:name = "laiden", typed = "laiden" 輸出:true 解釋:長按名字中的字元並不是必要的。
C
bool isLongPressedName(char* name, char* typed) { int m=strlen(name); int n=strlen(typed); if(m==0) { return true; } if(m>n) { return false; } int* res1=(int*)malloc(sizeof(int)*m); int* res2=(int*)malloc(sizeof(int)*n); int k1=0; int k2=0; int count=1; for(int i=1;i<m;i++) { if(name[i]==name[i-1]) { count++; } else { res1[k1]=count; k1++; count=1; } } res1[k1]=count; k1++; count=1; for(int i=1;i<n;i++) { if(typed[i]==typed[i-1]) { count++; } else { res2[k2]=count; k2++; count=1; } } res2[k2]=count; k2++; if(k1>k2) { return false; } for(int i=0;i<k1;i++) { if(res1[i]>res2[i]) { return false; } } return true; }
C++
class Solution { public: bool isLongPressedName(string name, string typed) { int m=name.length(); int n=typed.length(); if(m>n) { return false; } if(m==0) { return true; } vector<int> res1; vector<int> res2; int count=1; for(int i=1;i<m;i++) { if(name[i]==name[i-1]) { count++; } else { res1.push_back(count); count=1; } } res1.push_back(count); count=1; for(int i=1;i<n;i++) { if(typed[i]==typed[i-1]) { count++; } else { res2.push_back(count); count=1; } } res2.push_back(count); if(res1.size()>res2.size()) { return false; } for(int i=0;i<res1.size();i++) { if(res1[i]>res2[i]) { return false; } } return true; } };
python
class Solution:
def isLongPressedName(self, name, typed):
"""
:type name: str
:type typed: str
:rtype: bool
"""
m=len(name)
n=len(typed)
if m==0:
return True
if m>n:
return False
res1=[]
res2=[]
count=1
for i in range(1,m):
if name[i]==name[i-1]:
count+=1
else:
res1.append(count)
count=1
res1.append(count)
count=1
for i in range(1,n):
if typed[i]==typed[i-1]:
count+=1
else:
res2.append(count)
count=1
res2.append(count)
if len(res1)>len(res2):
return False
for i in range(0,len(res1)):
if res1[i]>res2[i]:
return False
return True