【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用户

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/109194170