925.Long Pressed Name

925.Long Pressed Name

难度:Easy

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 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 of name and typed are lowercase letters.

首先可以確定如果輸入的字串長度小於name的話,直接返回false。另外從name的起點來時判斷,對輸入字串遍歷一遍,如果前一個和後一個相等,則看name的前後是否相等,如果相等,則計數器start後移,如果不相等則保持不變。如果輸入字串不相等,也直接加1.碰到name和輸入字串相應位置不等的情況,直接返回false。最後看start是否走到了name的末尾,如果沒有就返回false,否則返回true。

class Solution {
public:
bool isLongPressedName(string name, string typed) {
if(typed.length()<name.length()) return false;
int start=0;
for(int i=0;i<typed.size();i++)
{
if(typed[i]!=name[start]) return false;
else if(i<typed.size()-1 && typed[i] == typed[i+1]){
if(start<name.size()-1 && name[start] == name[start+1])
start++;
}
else
start++;
}
return start==name.size();
}
};

执行用时 :0 ms, 在所有 C++ 提交中击败了100.00%的用户 内存消耗 :8.5 MB, 在所有 C++ 提交中击败了77.52%的用户