Backspace String Compare
You're given two strings s and t made of lowercase letters and '#' characters. Each '#' is a backspace that deletes the character typed just before it; a backspace on empty text does nothing. Type each string into its own empty text editor and return true if both editors end up with the same text, and false otherwise.
Examples
s = "ab#c", t = "ad#c" returns true
The backspace removes the b in s and the d in t, so both become "ac".
s = "ab##", t = "c#d#" returns true
Two backspaces in a row erase both letters of s, and t erases each letter right after typing it. Both end up empty.
s = "a#c", t = "b" returns false
s becomes "c" and t stays "b", so they differ.
Constraints
- 1 <= s.length, t.length <= 200
- s and t contain only lowercase letters and '#' characters.
Hints
When you hit a backspace, which character does it erase?
Use a stack: typing a letter pushes it, and a backspace pops the top.
For each string, push letters onto a stack and pop on '#' if the stack is not empty. Return whether the two resulting stacks are equal.
Drill This: Your Approach First
Approach
A backspace always removes the most recently typed character still on screen, which is exactly a stack's pop. Replay each string onto its own stack: push every letter, and pop on '#' when the stack is not empty. Then compare the two stacks. In Java a StringBuilder works as the stack. For O(1) extra space, walk both strings from the end with two pointers, counting pending backspaces to skip the characters they erase.
Time
O(n + m)
Space
O(n + m)
Pitfall
Solutions
class Solution {
public boolean backspaceCompare(String s, String t) {
return build(s).equals(build(t));
}
private String build(String text) {
StringBuilder stack = new StringBuilder();
for (char c : text.toCharArray()) {
if (c != '#') stack.append(c);
else if (stack.length() > 0) stack.deleteCharAt(stack.length() - 1);
}
return stack.toString();
}
}class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
def build(text):
stack = []
for c in text:
if c != '#':
stack.append(c)
elif stack:
stack.pop()
return stack
return build(s) == build(t)