LeetCode 925. Long Pressed Name
考点 | 难度 |
---|---|
Two Pointers | Easy |
题目
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.
思路
用two pointers方法,如果typed和name相同位置的字母不一样,检查typed里这位和前一位是不是一样。如果不一样说明不是重复,返回false
答案
public boolean isLongPressedName(String name, String typed) {
int i = 0, m = name.length(), n = typed.length();
for (int j = 0; j < n; ++j)
if (i < m && name.charAt(i) == typed.charAt(j))
++i;
else if (j == 0 || typed.charAt(j) != typed.charAt(j - 1))
return false;
return i == m;
}