925. Long Pressed Name #
Problem #
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:
Input: name = "alex", typed = "aaleex"
Output: true
Explanation: 'a' and 'e' in 'alex' were long pressed.
Example 2:
Input: name = "saeed", typed = "ssaaedd"
Output: false
Explanation: 'e' must have been pressed twice, but it wasn't in the typed output.
Example 3:
Input: name = "leelee", typed = "lleeelee"
Output: true
Example 4:
Input: name = "laiden", typed = "laiden"
Output: true
Explanation: It's not necessary to long press any character.
Note:
- name.length <= 1000
- typed.length <= 1000
- The characters of name and typed are lowercase letters.
Problem Summary #
Given 2 strings, the latter string contains the former string. For example, during typing, a certain character may be pressed a few extra times. Determine whether the latter string has such a “long press” keyboard situation compared with the former string.
Solution Approach #
- This problem can also use the sliding window idea. Compare the 2 strings together; if the same characters are encountered, continue sliding the window backward. Until the first different character is encountered; if the two strings are not equal, return false directly. See the code for the specific implementation.
- The test cases for this problem were modified once. Pay attention to the second set of test cases I wrote here: after name ends, if typed still has extra different characters, this situation should output false. See the second, third, and fourth test cases in the test file for details.
Code #
package leetcode
func isLongPressedName(name string, typed string) bool {
if len(name) == 0 && len(typed) == 0 {
return true
}
if (len(name) == 0 && len(typed) != 0) || (len(name) != 0 && len(typed) == 0) {
return false
}
i, j := 0, 0
for i < len(name) && j < len(typed) {
if name[i] != typed[j] {
return false
}
for i < len(name) && j < len(typed) && name[i] == typed[j] {
i++
j++
}
for j < len(typed) && typed[j] == typed[j-1] {
j++
}
}
return i == len(name) && j == len(typed)
}