I was recently asked this question in an interview:
Given two strings s and t, return if they are equal when both are typed into empty text editors. # means a backspace character.
Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T become "ac".
I came up with below solution but it is not space efficient:
public static boolean sol(String s, String t) {
return helper(s).equals(helper(t));
}
public static String helper(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c != '#')
stack.push(c);
else if (!stack.empty())
stack.pop();
}
return String.valueOf(stack);
}
I wanted to see if there is any better way to solve this problem which doesn't use stack. I mean can we solve it in O(1) space complexity?
Note: we could have multiple backspace characters in as well.