Leetcode / 844. Backspace String Compare
Pick a programming language:
Here is the source code for the solution to this problem.
class Solution {
public boolean backspaceCompare(String s, String t) {
Stack<Character> stack1 = new Stack<Character>();
Stack<Character> stack2 = new Stack<Character>();
int size = Math.max(s.length(), t.length());
for (int i = 0; i < size; i++) {
if (i < s.length()) {
char c = s.charAt(i);
if (c == '#') {
if (!stack1.isEmpty()) {
stack1.pop();
}
}
else {
stack1.push(c);
}
}
if (i < t.length()) {
char c = t.charAt(i);
if (c == '#') {
if (!stack2.isEmpty()) {
stack2.pop();
}
}
else {
stack2.push(c);
}
}
}
if (stack1.size() != stack2.size()) {
return false;
}
int stackSize = stack1.size();
for (int i = 0; i < stackSize; i++) {
char c1 = stack1.pop();
char c2 = stack2.pop();
if (c1 != c2) {
return false;
}
}
return true;
}
}
Did you like the lesson? 😆👍
Consider a donation to support our work: