天天看点

字符匹配-leetcode-925. 长按键入

925. 长按键入

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

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

输入:name = "alex", typed = "aaleex"
输出:true
解释:'alex' 中的 'a' 和 'e' 被长按
      
输入:name = "laiden", typed = "laiden"
输出:true
解释:长按名字中的字符并不是必要的。
      
字符匹配-leetcode-925. 长按键入
字符匹配-leetcode-925. 长按键入
class Solution {
public:
    bool isLongPressedName(string name, string typed) {
        if(typed.length() < name.length())
            return false;
        int j = 0, i = 0;
        while(i < typed.length() && j < name.length()){
            if(name[j] == typed[i]){
                    i++;  j++;
            }
            else{
                if(j == 0)//如果第一个字符都不同,肯定就不一样
                    return false;

                while(typed[i] == typed[i-1])//重复,typed继续往前懂
                    i++;
                if(typed[i] == name[j]){
                    i++; j++;
                }
                else
                return false;
            }
        }
        if(j < name.length())
            return false;
        while(i < typed.length()){
            if(typed[i] == typed[i-1])
                i++;
            else
                return false;
        }
        return true;
    }
};