LeetCode925-长按键入

题目链接

英文链接:https://leetcode.com/problems/long-pressed-name/

中文链接:https://leetcode-cn.com/problems/long-pressed-name/

题目详述

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

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

示例 1:

1
2
3
输入:name = "alex", typed = "aaleex"
输出:true
解释:'alex' 中的 'a' 和 'e' 被长按。

示例 2:

1
2
3
输入:name = "saeed", typed = "ssaaedd"
输出:false
解释:'e' 一定需要被键入两次,但在 typed 的输出中不是这样。

示例 3:

1
2
输入:name = "leelee", typed = "lleeelee"
输出:true

示例 4:

1
2
3
输入:name = "laiden", typed = "laiden"
输出:true
解释:长按名字中的字符并不是必要的。

提示:

  1. name.length <= 1000
  2. typed.length <= 1000
  3. nametyped 的字符都是小写字母。

题目详解

  • 运用双指针。一个指针 i 指向 name 数组,一个指针 j 指向 typed 数组。
  • name[i] == typed[j] 时,指针 ij 均右移。
  • name[i] != typed[j] 时,
    • j > 0 && typed[j] == typed[j - 1],可能是长按,存在匹配的可能,j 右移。
    • j == 0 || typed[j] != typed[j - 1],不可能匹配,返回 false
  • 最后还需判断是否存在多余不同的字符。
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
31
public class LeetCode_00925 {

public boolean isLongPressedName(String name, String typed) {
if (name.length() > typed.length()) {
return false;
}
char[] cn = name.toCharArray();
char[] ct = typed.toCharArray();
int i = 0, j = 0;
while (i < cn.length && j < ct.length) {
if (cn[i] == ct[j]) {
++i;
} else if (j == 0 || ct[j] != ct[j - 1]) {
return false;
}
++j;
}
if (i != cn.length) {
return false;
}
// 判断是否存在多余不同的字符
if (j > 0) {
for (; j < ct.length; ++j) {
if (ct[j] != ct[j - 1]) {
return false;
}
}
}
return true;
}
}