-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBackspace.java
More file actions
30 lines (26 loc) · 891 Bytes
/
Copy pathBackspace.java
File metadata and controls
30 lines (26 loc) · 891 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
package LeetcodePractice;
import java.util.Stack;
public class Backspace {
public boolean backspaceCompare(String s, String t) {
return build(s).equals(build(t));
}
private String build(String str) {
Stack<Character> stack = new Stack<>();
for (char c : str.toCharArray()) {
if (c != '#') {
stack.push(c);
} else if (!stack.isEmpty()) {
stack.pop();
}
}
StringBuilder sb = new StringBuilder();
for (char c : stack) sb.append(c);
return sb.toString();
}
public static void main(String[] args) {
Backspace sol = new Backspace();
System.out.println(sol.backspaceCompare("ab#c", "ad#c"));
System.out.println(sol.backspaceCompare("ab##", "c#d#"));
System.out.println(sol.backspaceCompare("a#c", "b"));
}
}