-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathBackspace String Compare.txt
38 lines (30 loc) Β· 1.03 KB
/
Backspace String Compare.txt
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
36
37
38
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
String t = sc.nextLine();
String result1 = processString(s);
String result2 = processString(t);
boolean isEqual = result1.equals(result2);
System.out.println(isEqual);
}
public static String processString(String str) {
Stack<Character> stack = new Stack<>();
for (char c : str.toCharArray()) {
if (c == '#') {
if (!stack.isEmpty()) {
stack.pop(); // Simulate backspace by popping from the stack.
}
} else {
stack.push(c);
}
}
// Convert the stack back to a string.
StringBuilder result = new StringBuilder();
while (!stack.isEmpty()) {
result.insert(0, stack.pop());
}
return result.toString();
}
}