[LeetCode] 925. 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 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:

  1. name.length <= 1000
  2. typed.length <= 1000
  3. The characters of name and typed are lowercase letters.

這道題說是你朋友在用鍵盤敲入名字的時候,對於某個字母可能會長時間按鍵,這導可能會有多個相同字母輸入,這種情況是允許的,現在給了兩個字符串,name 是朋友的名字,typed 是朋友敲入的字符串,問 typed 是否是朋友敲入的名字。其實這道題的本質是,對於 name 中每個位置的字母,對應在 typed 中的出現次數一定要相等或者更多,但是直接統計每個字符出現的次數是不對的,因為位置關系很重要,比如 abb 和 abab,雖然后者中a和b的出現次數都大於等於前者,但還是要返回 false。博主最先想的方法是用兩個指針i和j分別提取 name 和 typed 字符串中每個字母出現的次數,如果 typed 中的次數小於 name 中的次數,則直接返回 false 即可,最終循環結束后,i和j應該分別為 name 和 typed 的長度,此時返回 true,否則返回 false,參見代碼如下:
解法一:
class Solution {
public:
    bool isLongPressedName(string name, string typed) {
        int i = 0, j = 0, m = name.size(), n = typed.size();
        while (i < m || j < n) {
            int start1 = i, start2 = j;
            while (i < m - 1 && name[i] == name[i + 1]) ++i;
            while (j < n - 1 && typed[j] == typed[j + 1]) ++j;
            if (j - start2 + 1 < i - start1 + 1) return false;
            ++i; ++j;
        }
        return i == m && j == n;
    }
};

可以寫的簡潔一些,不需要使用那么多的 while 循環,而是直接用j遍歷 typed 中每個字母,i初識時指向 name 的第一個字母,假如i小於m,且 name[i] 等於 typed[j-1] 時,則i自增1,否則的話,若此時j為0(說明第一個字母就不匹配),或者 typed[j] 不等於 typed[j - 1](說明出現了無法匹配的新字母),則直接返回 false。循環退出后若i等於m則返回 true,否則返回 false,參見代碼如下:
解法二:
class Solution {
public:
    bool isLongPressedName(string name, string typed) {
        int i = 0, m = name.size(), n = typed.size();
        for (int j = 0; j < n; ++j) {
            if (i < m && name[i] == typed[j]) ++i;
            else if (!j || typed[j] != typed[j - 1]) return false;
        }
        return i == m;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/925


參考資料:

https://leetcode.com/problems/long-pressed-name/

https://leetcode.com/problems/long-pressed-name/discuss/183994/C%2B%2BJavaPython-Two-Pointers

https://leetcode.com/problems/long-pressed-name/discuss/183929/C%2B%2B-2-lines-accepted-and-5-lines-accurate


[LeetCode All in One 題目講解匯總(持續更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM