Long Pressed Name
Your friend typed your name but some characters may have been pressed too long. Given the name you intended and the typed string, return true if typed could be a long-pressed version of name.
Example 1
Input: name="alex", typed="aaleex" → Output: true
Example 2
Input: name="saeed", typed="ssaaedd" → Output: false
Solution Approach
Two pointers: match each character of name with typed. Consecutive duplicates in typed are allowed.
- i pointer on name, j pointer on typed.
- While j < typed.length:
- If name[i]==typed[j]: advance both.
- Else if j>0 and typed[j]==typed[j-1]: advance j (long press).
- Else return false.
- Return i == name.length.
Java
class Solution {
public boolean isLongPressedName(String name, String typed) {
int i = 0, j = 0;
while (j < typed.length()) {
if (i < name.length() && name.charAt(i) == typed.charAt(j)) {
i++; j++;
} else if (j > 0 && typed.charAt(j) == typed.charAt(j - 1)) {
j++;
} else {
return false;
}
}
return i == name.length();
}
}
- Time Complexity: O(N+M)
- Space Complexity: O(1)