Long Pressed Name

本文介绍了一种算法,用于判断给定的两个字符串中,第二个字符串是否可以通过第一个字符串的字符长按输入得到。通过使用双指针技巧,确保name中的字符频率不超过typed中的频率,从而实现对长按输入的有效判断。
摘要由CSDN通过智能技术生成

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

思路:双指针,这里比较巧妙的是,用了count,也就是说,name里面的char频率必须小于typed里面的频率。最后记得i,j都必须同时到达最后的length;

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值