Leetcode 925. Long Pressed Name
Suppose your friend is typing his name
into a keyboard. Sometimes, when typing a character c
, the key might get long pressed, and the character might be typed one or more times.
You examine the typed characters of the keyboard. Return True
if it is possible that it was your friend’s 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
Constraints:
1 <= name.length, typed.length <= 1000
name
and typed
consist of only lowercase English letters.name
and typed
will only contain lowercase English letters?
We can solve this problem using a two-pointer technique. The idea is to iterate through both strings simultaneously, comparing characters and handling long presses as needed.
i
for name
and j
for typed
.typed
string with pointer j
:
typed[j]
matches the character at name[i]
, move both pointers i
and j
forward.typed[j]
matches typed[j-1]
(indicating a long press). If it does, only move j
forward.false
because the strings don’t match the criteria.name
(i.e., i == name.length()
).class Solution {
public:
bool isLongPressedName(string name, string typed) {
int i = 0, j = 0;
while (j < typed.length()) {
if (i < name.length() && name[i] == typed[j]) {
i++;
j++;
} else if (j > 0 && typed[j] == typed[j - 1]) {
j++;
} else {
return false;
}
}
return i == name.length();
}
};
O(n)
, where n
is the length of the typed
string. This is because each character in typed
is processed at most once.O(1)
since we are using only a few extra variables.This approach ensures that we efficiently check if typed
can be derived from name
considering the long press scenario.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?