你的朋友正在使用键盘输入他的名字 name。偶尔,在键入字符 c 时,按键可能会被长按,而字符可能被输入 1 次或多次。
你将会检查键盘输入的字符 typed。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True。
我的解法:
class Solution: def isLongPressedName(self, name: str, typed: str) -> bool: list1 = self.helper(name) list2 = self.helper(typed) if len(list1) != len(list2): return False for i in range(len(list1)): if list1[i][0] != list2[i][0] or list1[i][1] > list2[i][1]: return False return True def helper(self, s): c, cnt = '$', 1 list1 = [] for i in range(len(s)): if s[i] == c: cnt += 1 else: list1.append((c, cnt)) cnt = 1 c = s[i] list1.append((c, cnt)) return list1[1:]标准双指针解法:
class Solution { public boolean isLongPressedName(String name, String typed) { int i = 0, j = 0; while (j < typed.length()) { if (i < name.length() && name.charAt(i) == typed.charAt(j)) { i++; j++; } else if (j > 0 && typed.charAt(j) == typed.charAt(j - 1)) { j++; } else { return false; } } return i == name.length(); } }官方给出的双指针写法空间复杂度较低。
