925. Long Pressed Name
Explanation
To solve this problem, we can iterate through both the name
and typed
strings simultaneously. We keep track of the current characters being compared in both strings. If the characters match, we move to the next characters in both strings. If they don't match, we check if the current character in typed
is the same as the previous character in typed
. If it is, this means the current character in typed
might have been long pressed, so we move to the next character in typed
and continue comparing. At the end, if we reach the end of both strings, it means the typed
string can be formed by long-pressing the name
string.
Time complexity: O(n), where n is the length of the longer of the two input strings.
Space complexity: O(1)
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();
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.