844. Backspace String Compare
Explanation
To solve this problem, we can use a stack to simulate the typing process for both strings. We iterate over each character in the input strings, and if we encounter a character that is not a backspace ('#'
), we push it onto the stack. If we encounter a backspace character, we pop the top character from the stack.
After iterating through both strings, we compare the characters left in the stacks for s
and t
. If the characters in the stacks are equal, then the strings are equal after applying backspaces.
Time Complexity: O(n) where n is the length of the longer string among s
and t
.
Space Complexity: O(n)
class Solution {
public boolean backspaceCompare(String s, String t) {
return buildString(s).equals(buildString(t));
}
private String buildString(String str) {
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray()) {
if (c != '#') {
sb.append(c);
} else if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
}
return sb.toString();
}
}
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.