# 长按输入(925)
# 题目
你的朋友正在使用键盘输入他的名字 name
。偶尔,在键入字符 c 时,按键可能会被长按,而字符可能被输入 1 次或多次。
你将会检查键盘输入的字符 typed
。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True
。
# 示例
输入:name = "alex"
, typed = "aaleex"
输出:true
输入:name = "saeed"
, typed = "ssaaedd"
输出:false
输入:name = "leelee"
, typed = "lleeelee"
输出:true
输入:name = "laiden"
, typed = "laiden"
输出:true
# 提示
name.length <= 1000
typed.length <= 1000
name 和 typed 的字符都是小写字母。
1
2
3
2
3
# 算法
# 双指针
export const isLongPressedName = (name, typed) => {
let l = 0;
let r = 0;
while (l < name.length || r < typed.length) {
if (name[l] !== typed[r]) {
return false;
}
// 当检索到name最后一项时,如果匹配typed,则不继续检查输入,直接返回成功
if (l === name.length - 1 && name[l] === typed[r]) {
return true;
}
if (name[l + 1] === name[l]) {
l++;
r++;
continue;
}
// 如果name下一位不同,则连续跳过typed的重复字符
if (name[l + 1] !== name[l]) {
while (typed[r + 1] === typed[r]) {
r++;
}
l++;
r++;
continue;
}
}
return true;
};
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
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
← 长按输入(925) 罗马数字转整数(13) →