forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBackspaceStringCompare.java
More file actions
35 lines (32 loc) · 950 Bytes
/
BackspaceStringCompare.java
File metadata and controls
35 lines (32 loc) · 950 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.util.Stack;
public class BackspaceStringCompare {
public boolean backspaceCompare(String S, String T) {
Stack<Character> stack1 = new Stack<>();
Stack<Character> stack2 = new Stack<>();
for (int i = 0; i < S.length(); i++) {
helper(stack1, S, i);
}
for (int i = 0; i < T.length(); i++) {
helper(stack2, T, i);
}
while (!stack1.isEmpty() && !stack2.isEmpty()) {
if (!stack1.pop().equals(stack2.pop())) {
return false;
}
}
return stack1.isEmpty() && stack2.isEmpty();
}
private void helper(Stack<Character> stack, String s, int i) {
if (i >= s.length()) {
return;
}
char c = s.charAt(i);
if (c == '#') {
if (!stack.isEmpty()) {
stack.pop();
}
} else {
stack.push(c);
}
}
}