Loading

LeetCode problem#844

Backspace String Compare

Solved in 1 languageJava

Solve it on LeetCode(opens in a new tab)

Solution

51 lines
1class Solution {
2    public boolean backspaceCompare(String s, String t) {
3        Stack<Character> stack1 = new Stack<Character>();
4        Stack<Character> stack2 = new Stack<Character>();
5        int size = Math.max(s.length(), t.length());
6
7        for (int i = 0; i < size; i++) {
8            if (i < s.length()) {
9                char c = s.charAt(i);
10                
11                if (c == '#') {
12                    if (!stack1.isEmpty()) {
13                        stack1.pop();
14                    }
15                }
16                else {
17                    stack1.push(c);
18                }
19            }
20
21            if (i < t.length()) {
22                char c = t.charAt(i);
23                
24                if (c == '#') {
25                    if (!stack2.isEmpty()) {
26                        stack2.pop();
27                    }
28                }
29                else {
30                    stack2.push(c);
31                }
32            }
33        }
34
35        if (stack1.size() != stack2.size()) {
36            return false;
37        }
38
39        int stackSize = stack1.size();
40        for (int i = 0; i < stackSize; i++) {
41            char c1 = stack1.pop();
42            char c2 = stack2.pop();
43
44            if (c1 != c2) {
45                return false;
46            }
47        }
48
49        return true;
50    }
51}

Want a walkthrough of this Java solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.