Q:
你的朋友正在使用键盘输入他的名字 name
。偶尔,在键入字符 c
时,按键可能会被长按,而字符可能被输入 1 次或多次。
你将会检查键盘输入的字符 typed
。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True
。
示例 1:
输入:name = "alex", typed = "aaleex"
输出:true
解释:'alex' 中的 'a' 和 'e' 被长按。
思路:
typed 字符串中相连的字符数量应当大于name中相连的字符数量,使用双指针解决 失败
使用堆栈解决 失败
使用压缩字符串的方式,通过了 写的挺乱的 大概就是压缩一下字符串 然后比较
比如leelee 压缩为 l1e2l1e1,同理 lleeelee 压缩为 l2e3l1e2 然后比较奇数位是否相同 偶数位typed的数量是否大于name
代码如下:
class Solution:
def isLongPressedName(self, name, typed):
"""
:type name: str
:type typed: str
:rtype: bool
"""
if name == typed:
return True
s1 = self.build(name)
s2 = self.build(typed)
if len(s1) != len(s2):
return False
else:
i = 0
while(i < len(s1)):
if i % 2 == 0:
if s1[i] != s2[i]:
return False
else:
if int(s1[i]) > int(s2[i]):
return False
i+=1
return True
def build(self,inputs):
res = ''
slow = 0
fast = 1
while (fast < len(inputs)):
if inputs[slow] == inputs[fast]:
fast += 1
else:
res += inputs[slow]+str(fast-slow)
slow = fast
fast += 1
res += inputs[slow] + str(fast - slow)
return res