LeetCode 题解工作台
长按键入
你的朋友正在使用键盘输入他的名字 name 。偶尔,在键入字符 c 时,按键可能会被 长按 ,而字符可能被输入 1 次或多次。 你将会检查键盘输入的字符 typed 。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True 。 示例 1: 输入: name = "alex"…
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · 双·指针·invariant
答案摘要
我们利用两个指针 和 分别指向字符串 和 的第一个字符,然后开始遍历,如果 $\textit{typed}[j] \neq \textit{name}[i]$,说明两个字符串不匹配,直接返回 。否则,我们找到连续相同的字符的下一个位置,分别记为 和 ,如果 $x - i > y - j$,说明 中的字符个数小于 中的字符个数,直接返回 。否则,我们将 和 更新为 和 ,继续遍历…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
你的朋友正在使用键盘输入他的名字 name。偶尔,在键入字符 c 时,按键可能会被长按,而字符可能被输入 1 次或多次。
你将会检查键盘输入的字符 typed。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True。
示例 1:
输入:name = "alex", typed = "aaleex" 输出:true 解释:'alex' 中的 'a' 和 'e' 被长按。
示例 2:
输入:name = "saeed", typed = "ssaaedd" 输出:false 解释:'e' 一定需要被键入两次,但在 typed 的输出中不是这样。
提示:
1 <= name.length, typed.length <= 1000name和typed的字符都是小写字母
解题思路
方法一:双指针
我们利用两个指针 和 分别指向字符串 和 的第一个字符,然后开始遍历,如果 ,说明两个字符串不匹配,直接返回 。否则,我们找到连续相同的字符的下一个位置,分别记为 和 ,如果 ,说明 中的字符个数小于 中的字符个数,直接返回 。否则,我们将 和 更新为 和 ,继续遍历,直到 和 分别遍历完 和 ,返回 。
时间复杂度 ,其中 和 分别是字符串 和 的长度。空间复杂度 。
class Solution:
def isLongPressedName(self, name: str, typed: str) -> bool:
m, n = len(name), len(typed)
i = j = 0
while i < m and j < n:
if name[i] != typed[j]:
return False
x = i + 1
while x < m and name[x] == name[i]:
x += 1
y = j + 1
while y < n and typed[y] == typed[j]:
y += 1
if x - i > y - j:
return False
i, j = x, y
return i == m and j == n
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n + m) where n and m are the lengths of name and typed because each pointer scans its string once. Space complexity is O(1) as no extra data structures are used beyond pointer variables. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expect linear scanning solutions rather than nested loops.
- question_mark
Check edge cases like repeated characters at the start or end of typed.
- question_mark
Clarify whether empty strings or single-character names are possible inputs.
常见陷阱
外企场景- error
Assuming all repeated characters are valid without matching the name sequence.
- error
Failing to check the final position of the name pointer after traversal.
- error
Ignoring consecutive repeated characters at the start or end of typed.
进阶变体
外企场景- arrow_right_alt
Allow uppercase letters and consider case-sensitive matching.
- arrow_right_alt
Count minimal number of long presses required to produce typed from name.
- arrow_right_alt
Check if typed can result from name with both long presses and skipped characters.