题目链接:https://leetcode.com/problems/long-pressed-name/description/
Example 1:
1Input: name = "alex", typed = "aaleex" 2Output: true 3Explanation: 'a' and 'e' in 'alex' were long pressed.
Example 2:
1Input: name = "saeed", typed = "ssaaedd" 2Output: false 3Explanation: 'e' must have been pressed twice, but it wasn't in the typed output.
Example 3:
1Input: name = "leelee", typed = "lleeelee" 2Output: true
Example 4:
1Input: name = "laiden", typed = "laiden" 2Output: true 3Explanation: It's not necessary to long press any character.
Note:
name.length <= 1000typed.length <= 1000- The characters of
nameandtypedare lowercase letters.
思路:
- 若typed 符合要求,则typed 的 length(长度)满足条件:typed.length() >= name.length();
- i, j分别是指向name 和 typed的下标,i, j下标初始值都为0;
- 当 name[i] == typed[j] 时,i, j 向后移动一个单位;
- 当 name[i] != typed[j] 时,判断 typed[j] 是否等于name[i-1] (name[i-1] == typed[j-1]);
-
- 若 typed[j] != name[j-1] 则 typed 不满足,返回false。
- 若 **typed[j] == name[i-1],**则 **++j,**直至 typed[j] != name[i-1],执行****步骤2。
注意:根据上面的分析,需要用一个字符变量来存储**name[i]**的值,该字符变量初始化为空字符。
编码如下:
1 1 class Solution { 2 2 public: 3 3 bool isLongPressedName(string name, string typed) { 4 4 if (name.length() > typed.length()) return false; 5 5 6 6 char pre = ' '; 7 7 int indexOfName = 0; 8 8 9 9 for (int i = 0; i < typed.length(); ++i) 1010 { 1111 if (name[indexOfName] != typed[i] && pre == ' ') 1212 return false; 1313 1414 if (name[indexOfName] == typed[i]) 1515 { 1616 pre = name[indexOfName]; 1717 indexOfName++; 1818 } 1919 else 2020 { 2121 if (pre == typed[i]) 2222 continue; 2323 else 2424 return false; 2525 } 2626 } 2727 2828 if (indexOfName != name.length()) return false; 2929 3030 return true; 3131 } 3232 };