Your friend is typing his
name
into a keyboard. Sometimes, when typing a characterc
, the key might get long pressed, and the character will be typed 1 or more times.You examine the
typed
characters of the keyboard. ReturnTrue
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.
思路:O(n)同时遍历两个字符串,如果不相同,看第二个字符串这个位和前面的是否相同,相同则后移继续判断,直到其中一个结束,判断剩余串。
class Solution {
public:
bool isLongPressedName(string name, string typed) {
int l1 = name.length();
int l2 = typed.length();
bool flag=true;
int i,j=0;
for(i=0;i<l1&&j<l2;i++)
{
if(name[i]!=typed[j])
{
if(j>0&&j<l2)
{
while(typed[j]==typed[j-1]&&j<l2-1) j++;
if(typed[j]!=name[i]) flag=false;
}
else flag=false;
}
j++;
}
if(i!=l1) flag=false;
for(;j<l2;j++)
{
if(typed[j]!=typed[j-1])
{
flag=false;
break;
}
}
return flag;
}
};