【leetcode Weekly Contest 107】 925. Long Pressed Name

本文介绍了一种用于判断输入字符串是否可能由键盘长按操作产生的算法。通过O(n)的时间复杂度,同时遍历两个字符串,比较字符,当遇到不匹配时检查是否存在长按操作。算法最终返回输入是否符合预期的名称。

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

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.

思路:O(n)同时遍历两个字符串,如果不相同,看第二个字符串这个位和前面的是否相同,相同则后移继续判断,直到其中一个结束,判断剩余串。

class Solution {
public:
    bool isLongPressedName(string name, string typed) {
        int l1 = name.length();
        int l2 = typed.length();
        bool flag=true;
        int i,j=0;
        for(i=0;i<l1&&j<l2;i++)
        {
            if(name[i]!=typed[j])
            {
                if(j>0&&j<l2)
                {
                       while(typed[j]==typed[j-1]&&j<l2-1) j++;
                       if(typed[j]!=name[i]) flag=false;
                }   
                else flag=false;
            }
            j++;
        }
        if(i!=l1) flag=false;
        for(;j<l2;j++)
        {
            if(typed[j]!=typed[j-1])
            {
                flag=false;
                break;
            }
        }
        return flag;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值