leetcode-9-长按键入

Long pressed name

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:

Input: name = “alex”, typed = “aaleex”
Output: true
Explanation: ‘a’ and ‘e’ in ‘alex’ were long pressed.

Example:

Input: name = “saeed”, typed = “ssaaedd”
Output: false
Explanation: ‘e’ must have been pressed twice, but it wasn’t in the typed output.

Example:

Input: name = “leelee”, typed = “lleeelee”
Output: true

Example:

Input: name = “laiden”, typed = “laiden”
Output: true
Explanation: It’s not necessary to long press any character.

一个月没做题了,刚开始很没有头绪,不知道怎么做,没办法去看了评论。
用双重游标,name和typed同时扫描,二者相同++,不同时判断是否是long pressed。跳出循环有两个条件,分别对两个条件进行正确性判断

class Solution {
public:
    bool isLongPressedName(string name, string typed) {
        int nindex = 0;
        int tindex = 0;
        bool flag = true;
        while(nindex < name.length() && tindex < typed.length())
        {
            if(name[nindex] == typed[tindex])
            {
                nindex++;
                tindex++;
            }else
            {
                if(nindex==0)
                    return false;
                if(typed[tindex] == typed[tindex-1])
                    tindex++;
                else
                    return false;
            }
        }
        while(tindex<typed.length())
        {
            if(typed[tindex] == typed[tindex-1])
                tindex++;
            else
                return false;
        }
        if(nindex < name.length() && tindex == typed.length())
            return false;
        return flag;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值