[Solved] Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character


The first mistake is pushing all the characters on the stack outside of the if statement.

Also you should check if stack is empty before removing items from it.
Otherwise EmptyStackException is thrown.

// stack1.push(S.charAt(i)); <-- remove this line
if (S.charAt(i)!='#') {
   stack1.push(S.charAt(i));
}else if (!stack1.isEmpty()) { // <-- add this check
   stack1.pop();
}

The second mistake is you can’t use == to compare the contents of two stacks, use .equals method instead:

if(stack1.equals(stack2))

5

solved Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character