Long pressed name
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 the typed 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:
Input: name = “alex”, typed = “aaleex”
Output: true
Explanation: ‘a’ and ‘e’ in ‘alex’ were long pressed.
Example:
Input: name = “saeed”, typed = “ssaaedd”
Output: false
Explanation: ‘e’ must have been pressed twice, but it wasn’t in the typed output.
Example:
Input: name = “leelee”, typed = “lleeelee”
Output: true
Example:
Input: name = “laiden”, typed = “laiden”
Output: true
Explanation: It’s not necessary to long press any character.
一个月没做题了,刚开始很没有头绪,不知道怎么做,没办法去看了评论。
用双重游标,name和typed同时扫描,二者相同++,不同时判断是否是long pressed。跳出循环有两个条件,分别对两个条件进行正确性判断
class Solution {
public:
bool isLongPressedName(string name, string typed) {
int nindex = 0;
int tindex = 0;
bool flag = true;
while(nindex < name.length() && tindex < typed.length())
{
if(name[nindex] == typed[tindex])
{
nindex++;
tindex++;
}else
{
if(nindex==0)
return false;
if(typed[tindex] == typed[tindex-1])
tindex++;
else
return false;
}
}
while(tindex<typed.length())
{
if(typed[tindex] == typed[tindex-1])
tindex++;
else
return false;
}
if(nindex < name.length() && tindex == typed.length())
return false;
return flag;
}
};