Your friend is typing hisname
into a keyboard. Sometimes, when typing a characterc
, the key might getlong pressed, and the character will be typed 1 or more times.
You examine thetyped
characters of the keyboard. ReturnTrue
if it is possible that it was your friends name, with some characters (possibly none) being long pressed.
这道题千万要注意一点,不是简单的统计字符的个数,因为这里面还有顺序的因素,比如abc和bca虽然字符相同,但是不符合条件。正确的做法就是two pointers,考虑顺序因素
class Solution {
public boolean isLongPressedName(String name, String typed) {
if(name == null && typed == null)
return true;
if(name == null || typed == null)
return true;
if(typed.length() < name.length())
return false;
int i = 0;
int j = 0;
while(i < name.length()) {
char c = name.charAt(i);
int count1 = 0;
int count2 = 0;
while(i < name.length() && name.charAt(i) == c) {
i++;
count1++;
}
while(j < typed.length() && typed.charAt(j) == c) {
j++;
count2++;
}
if(count2 < count1)
return false;
}
return true;
}
}