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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值