leetcode-925-Long-Pressed-Name

描述


Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times.

You examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed.

Example 1:

1
2
3
Input: name = "alex", typed = "aaleex"
Output: true
Explanation: 'a' and 'e' in 'alex' were long pressed.

Example 2:

1
2
3
Input: name = "saeed", typed = "ssaaedd"
Output: false
Explanation: 'e' must have been pressed twice, but it wasn't in the typed output.

Example 3:

1
2
Input: name = "leelee", typed = "lleeelee"
Output: true

Example 4:

1
2
3
Input: name = "laiden", typed = "laiden"
Output: true
Explanation: It's not necessary to long press any character.

Note:

  1. name.length <= 1000
  2. typed.length <= 1000
  3. The characters of name and typed are lowercase letters.

分析


利用双指针解决这个问题,遍历 typed 的指针走得更快,如果 typed 遍历完了,name 还没有遍历完,则返回 false。

解决方案1(Java)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public boolean isLongPressedName(String name, String typed) {
int typedIndex = -1;
for (char c: name.toCharArray()) {
typedIndex++;
while (true) {
if (typedIndex >= typed.length()) {
return false;
}
if (typed.charAt(typedIndex) != c) {
typedIndex++;
} else {
break;
}
}
}
return true;
}
}

题目来源