925.长按键入

长按键入

你的朋友正在使用键盘输入他的名字 name。偶尔,在键入字符 c 时,按键可能会被长按,而字符可能被输入 1 次或多次。

你将会检查键盘输入的字符 typed。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True。

示例 1:

输入:name = “alex”, typed = “aaleex”
输出:true

示例 2:

输入:name = “saeed”, typed = “ssaaedd”
输出:false

提示:

  • 1 <= name.length, typed.length <= 1000
  • name 和 typed 的字符都是小写字母

解析

使用双指针,同时遍历 name 和 typed,统计相同字符的连续次数,typed 中的次数必须大于等于 name 中的次数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
var isLongPressedName = function (name, typed) {
let i = 0,
j = 0;

while (i < name.length || j < typed.length) {
if (name[i] !== typed[j]) {
return false;
}

let countI = 0,
countJ = 0;
const char = name[i];

while (i < name.length && name[i] === char) {
i++;
countI++;
}

while (j < typed.length && typed[j] === char) {
j++;
countJ++;
}

if (countJ < countI) {
return false;
}
}

return true;
};

时间复杂度 O(n + m),空间复杂度 O(1)。


925.长按键入
https://leetcode.lz5z.com/925.long-pressed-name/
作者
tickli
发布于
2025年1月12日
许可协议