长按键入

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

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

class Solution {
   public boolean isLongPressedName(String name, String typed) {
       int len1=name.length();
       int len2=typed.length();
        if (len2< len1) {
            return false;
        }
        int i = 0;
        int j = 0;
        while (i < len1 && j < len2) {
            char n = name.charAt(i);
            char t = typed.charAt(j);

            if (n != t) {
                return false;
            }
            
            int cn = 0;
            while (i < name.length() && name.charAt(i) == n) {
                i++;
                cn++;
            }
            
            int ct = 0;
            while (j < typed.length() && typed.charAt(j) == n) {
                j++;
                ct++;
            }
            
            if (ct < cn) {
                return false;
            }
        }
        
        if (i != name.length() || j != typed.length()) {
            return false;
        }
        
        return true;
    }

}
发布了84 篇原创文章 · 获赞 12 · 访问量 1681

猜你喜欢

转载自blog.csdn.net/qq_42174669/article/details/104034598