LeetCode题925. 长按键入

it2025-03-24  7

题目描述: 你的朋友正在使用键盘输入他的名字 name。偶尔,在键入字符 c 时,按键可能会被长按,而字符可能 被输入 1 次或多次。你将会检查键盘输入的字符 typed。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True。 例子: 输入:name = "alex", typed = "aaleex" 输出:true 解释:'alex' 中的 'a' 和 'e' 被长按。 思路: 使用双指针,遍历键盘输入的字符typed和名字name,如果字符相同,就让两个指针同时向后移; 如果字符不同,且typed中当前字符与前一字符相同,则只移动typed的指针;否则就不会成功,直接返回false class Solution { public boolean isLongPressedName(String name, String typed) { int i = 0 ; int j = 0 ; while ( j < typed.length()){ //遍历typed if ( i < name.length() && name.charAt(i) == typed.charAt(j)){ i++ ; j++ ; }else if ( j > 0 && typed.charAt(j - 1) == typed.charAt(j)){ j++ ; }else { return false ; } } return i == name.length() ; } }
最新回复(0)