leetcode每日一题—925.长按键入

it2025-07-27  7

题目: 你的朋友正在使用键盘输入他的名字 name。偶尔,在键入字符 c 时,按键可能会被长按,而字符可能被输入 1 次或多次。 你将会检查键盘输入的字符 typed。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True。 解答:

方法1:

class Solution: def isLongPressedName(self, name: str, typed: str) -> bool: nl=len(name) tl=len(typed) if tl<nl: return False i=0 t=0 if name[i]!=typed[t]: return False while i<nl: if t==tl: return False for j in range(t,tl): if name[i]==typed[j]: t=j+1 break else: if j>0 and typed[j]!=typed[j-1]: return False if j==tl-1: return False i+=1 while t!=tl: if typed[t]!=typed[t-1]: return False t+=1 return True

方法2: 与方法1思想一致,但表述更为简单

class Solution: def isLongPressedName(self, name: str, typed: str) -> bool: # 定义指针 p = 0 q = 0 nl = len(name) tl = len(typed) while q < tl: # 比较,若相同,指针同步后移 if p < nl and name[p] == typed[q]: p += 1 q += 1 # 若不相同,要注意 p 指针指向的元素 # 如果是首元素,那么表示 name 和 typed 首字符都不同,可以直接返回 False # 如果不是首元素,看是否键入重复,键入重复,继续移动 q 指针,继续判断;如果不重复,直接返回 False,表示输入错误 elif p > 0 and name[p-1] == typed[q]: q += 1 else: return False # typed 遍历完成后要检查 name 是否遍历完成 return p == nl
最新回复(0)