LeetCode-Long Pressed Name

本文介绍了一种算法,用于判断在用户可能长按键盘字符的情况下,输入的字符串是否能匹配预设的名字字符串。通过遍历名字字符串并与输入字符串进行对比,确保即使有字符被长按,也能正确识别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description:
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:

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

题意:给定一个字符串name,及一个用户敲击的字符串typed;由于用户敲击键盘中的一个字符时可能时间较长,导致一个字符出现多次;现在考虑敲击时间过长的这种情况下,判断字符串typed是否与字符串name相符;

解法:遍历字符串name,假设遍历name的当前位置为i,我们只需要从字符串typed的当前位置出发,找到与字符name.charAt(i)相等的那个字符(如果存在的话);

Java
class Solution {
    public boolean isLongPressedName(String name, String typed) {
        int index = 0;
        for (int i = 0; i < name.length(); i++) {
            while (index < typed.length() && name.charAt(i) != typed.charAt(index)) index++;
            if (index >= typed.length()) return false;
            index++;
        }
        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值