天天看點

【LeetCode】 925. Long Pressed Name 長按鍵入(Easy)(JAVA)

【LeetCode】 925. Long Pressed Name 長按鍵入(Easy)(JAVA)

題目位址: https://leetcoden.com/problems/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.
           

Constraints:

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

題目大意

你的朋友正在使用鍵盤輸入他的名字 name。偶爾,在鍵入字元 c 時,按鍵可能會被長按,而字元可能被輸入 1 次或多次。

你将會檢查鍵盤輸入的字元 typed。如果它對應的可能是你的朋友的名字(其中一些字元可能被長按),那麼就傳回 True。

解題方法

1、name 和 typed 的第一個元素必須相等

2、如果 name 和 typed 的下一個元素不相等,name 的目前元素必須和 typed 的下一個元素相等

按照這兩個規則從 name 的開始周遊到結束即可

class Solution {
    public boolean isLongPressedName(String name, String typed) {
        if (name == null || name.length() == 0) return name == typed;
        int start = 0;
        for (int i = 0; i < name.length(); i++) {
            if (start >= typed.length() || name.charAt(i) != typed.charAt(start)) return false;
            start++;
            if (i < name.length() - 1 && start < typed.length() && name.charAt(i + 1) == typed.charAt(start)) {
                continue;
            }
            while (start < typed.length() && name.charAt(i) == typed.charAt(start)) {
                start++;
            }
        }
        return start == typed.length();
    }
}
           

執行耗時:1 ms,擊敗了86.83% 的Java使用者

記憶體消耗:36.7 MB,擊敗了63.24% 的Java使用者