首页 > 其他 > 详细

[LeetCode] 925. 长按键入

时间:2021-06-06 13:21:31      阅读:11      评论:0      收藏:0      [点我收藏+]

你的朋友正在使用键盘输入他的名字 name。偶尔,在键入字符 c 时,按键可能会被长按,而字符可能被输入 1 次或多次。

你将会检查键盘输入的字符 typed。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True。

 

示例 1:

输入:name = "alex", typed = "aaleex"
输出:true
解释:‘alex‘ 中的 ‘a‘ 和 ‘e‘ 被长按。
示例 2:

输入:name = "saeed", typed = "ssaaedd"
输出:false
解释:‘e‘ 一定需要被键入两次,但在 typed 的输出中不是这样。
示例 3:

输入:name = "leelee", typed = "lleeelee"
输出:true
示例 4:

输入:name = "laiden", typed = "laiden"
输出:true
解释:长按名字中的字符并不是必要的。
 

提示:

name.length <= 1000
typed.length <= 1000
name 和 typed 的字符都是小写字母。

使用双指针

    public boolean isLongPressedName(String name, String typed) {
        if (name == null || typed == null)
            return false;
        int nameIndex = 0;
        int typedIndex = 0;
        while (nameIndex < name.length() && typedIndex < typed.length()) {
            if (name.charAt(nameIndex) == typed.charAt(typedIndex)) {
                nameIndex++;
                typedIndex++;
            } else if (typedIndex > 0 && typed.charAt(typedIndex - 1) == typed.charAt(typedIndex)) {
                typedIndex++;
            } else {
                break;
            }
        }
        while (typedIndex < typed.length())
            if (typedIndex > 0 && typed.charAt(typedIndex - 1) == typed.charAt(typedIndex))
                typedIndex++;
            else
                break;
        return nameIndex >= name.length() && typedIndex >= typed.length();
    }

 

[LeetCode] 925. 长按键入

原文:https://www.cnblogs.com/luckygxf/p/14854794.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!