题目:
Your friend is typing his
name
into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times.
You examine thetyped
characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed.
Example 1:Input: name = "alex", typed = "aaleex" Output: true Explanation: 'a' and 'e' in 'alex' were long pressed.
Example 2:
Input: name = "saeed", typed = "ssaaedd" Output: false Explanation: 'e' must have been pressed twice, but it wasn't in the typed output.
Example 3:
Input: name = "leelee", typed = "lleeelee" Output: true
Example 4:
Input: name = "laiden", typed = "laiden" Output: true Explanation: It's not necessary to long press any character.
Note:
name.length <= 1000
typed.length <= 1000
The characters ofname
andtyped
are lowercase letters.
解释:
判断typed
是不是name
手抖多按(或者没有)某些字母的结果。
双指针法,一个指针idx1
指向name
,另一个指针idx2
指向typed
,关于指针的操作中文不好解释直接看代码…
python代码:
from collections import Counter
class Solution:
def isLongPressedName(self, name, typed):
"""
:type name: str
:type typed: str
:rtype: bool
"""
len1,len2=len(name),len(typed)
idx1,idx2=0,0
while idx1<len1 and idx2<len2:
if name[idx1]==typed[idx2]:
idx1+=1
idx2+=1
#不相等的话,有可能是typed重复了,操作之后idx2指向一个和前一个不一样的字母
elif idx2>0 and typed[idx2-1]==typed[idx2]:
idx2+=1
#如果排除了重复问题,还是不相等的话
else:
return False
#防止typed先被遍历完的情况
return idx1==len1
c++代码:
class Solution {
public:
bool isLongPressedName(string name, string typed) {
int len1=name.size();
int len2=typed.size();
int idx1=0,idx2=0;
while(idx1<len1 && idx2<len2)
{
if(name[idx1]==typed[idx2])
{
idx1++;
idx2++;
}
else if (idx2>0 &&typed[idx2-1]==typed[idx2])
idx2++;
else
return false;
}
return idx1==len1;
}
};
总结:
恩,主要是指针的操作。