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.
1
Example 1:
2
3
Input: name = "alex", typed = "aaleex"
4
Output: true
5
Explanation: 'a' and 'e' in 'alex' were long pressed.
6
Example 2:
7
8
Input: name = "saeed", typed = "ssaaedd"
9
Output: false
10
Explanation: 'e' must have been pressed twice, but it wasn't in the typed output.
11
Example 3:
12
13
Input: name = "leelee", typed = "lleeelee"
14
Output: true
15
Example 4:
16
17
Input: name = "laiden", typed = "laiden"
18
Output: true
19
Explanation: It's not necessary to long press any character.
20
21
22
Note:
23
24
name.length <= 1000
25
typed.length <= 1000
26
The characters of name and typed are lowercase letters.
Copied!
首先可以確定如果輸入的字串長度小於name的話,直接返回false。另外從name的起點來時判斷,對輸入字串遍歷一遍,如果前一個和後一個相等,則看name的前後是否相等,如果相等,則計數器start後移,如果不相等則保持不變。如果輸入字串不相等,也直接加1.碰到name和輸入字串相應位置不等的情況,直接返回false。最後看start是否走到了name的末尾,如果沒有就返回false,否則返回true。
1
class Solution {
2
public:
3
bool isLongPressedName(string name, string typed) {
4
if(typed.length()<name.length()) return false;
5
int start=0;
6
for(int i=0;i<typed.size();i++)
7
{
8
if(typed[i]!=name[start]) return false;
9
else if(i<typed.size()-1 && typed[i] == typed[i+1]){
10
if(start<name.size()-1 && name[start] == name[start+1])
11
start++;
12
}
13
else
14
start++;
15
}
16
return start==name.size();
17
}
18
};
Copied!
执行用时 :0 ms, 在所有 C++ 提交中击败了100.00%的用户 内存消耗 :8.5 MB, 在所有 C++ 提交中击败了77.52%的用户
Copy link