925. Long Pressed Name
阿新 • • 發佈:2018-11-03
題目連結:https://leetcode.com/problems/long-pressed-name/description/
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
typed
are 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 class Solution { 2 public: 3 bool isLongPressedName(string name, string typed) { 4 // name的長度 大於 typed的長度時不符合 5 if (name.length() > typed.length()) return false; 6 7 char pre = ' '; // 儲存name[i]的值,初始化為空字元 8 int indexOfName = 0; // 指示name的下標 9 10 for (int i = 0; i < typed.length(); ++i) 11 { 12 if (name[indexOfName] != typed[i] && pre == ' ') 13 return false; 14 15 if (name[indexOfName] == typed[i]) 16 { 17 pre = name[indexOfName]; 18 indexOfName++; 19 } 20 else 21 { 22 if (pre == typed[i]) 23 continue; 24 else 25 return false; 26 } 27 } 28 29 if (indexOfName != name.length()) return false; 30 31 return true; 32 33 } 34 35 };