力扣——长按键入

你的朋友正在使用键盘输入他的名字 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
解释:长按名字中的字符并不是必要的。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/long-pressed-name
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

官方解法
class Solution {
    public boolean isLongPressedName(String name, String typed) {
        int i = 0, j = 0;
        while(j < typed.length()) {
            if(i< name.length() && name.charAt(i) == typed.charAt(j)) {
                i++;
                j++;
            } else if(j > 0 && typed.charAt(j) == typed.charAt(j-1)) {
                j++;
            } else {
                return false;
            }
        }
        return i == name.length();
    }
}

执行用时:1 ms, 在所有 Java 提交中击败了86.83%的用户内存消耗:36.2 MB, 在所有 Java 提交中击败了99.24%的用户。

失忆笨拙解法
class Solution {
    public boolean isLongPressedName(String name, String typed) {
        if (name.equals(typed)) {
            return true;
        }
        char[] names = name.toCharArray();
        char[] typeds = typed.toCharArray();
        int n = 0;
        int t = 0;
        if (names[0] != typeds[0]) {
            return false;
        }
        while (t < typeds.length) {
            if (n < names.length && names[n] == typeds[t]) {
                n = n + 1;
                t = t + 1;
            } else {
                if (typeds[t] == typeds[t - 1]) {
                    t = t + 1;
                } else {
                    return false;
                }
            }
        }
        return n == names.length;
    }
}

执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户内存消耗:36.5 MB, 在所有 Java 提交中击败了87.81%的用户。

我是失忆,一个热爱技术的宅男,文章有任何问题您都可以在留言中指出。欢迎留言。

想一起的小伙伴可以加我微信,我们在路上,越走越远。

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

失忆老幺

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值