- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1047.java
36 lines (33 loc) · 1.12 KB
/
_1047.java
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
packagecom.fishercoder.solutions.secondthousand;
importjava.util.Deque;
importjava.util.LinkedList;
publicclass_1047 {
publicstaticclassSolution1 {
publicStringremoveDuplicates(StringS) {
StringBuildersb = newStringBuilder(S);
for (inti = 0; i < S.length() - 1; i++) {
if (S.charAt(i) == S.charAt(i + 1)) {
returnremoveDuplicates(S.substring(0, i) + S.substring(i + 2));
}
}
returnsb.toString();
}
}
publicstaticclassSolution2 {
publicStringremoveDuplicates(Strings) {
Deque<Character> stack = newLinkedList<>();
for (charc : s.toCharArray()) {
if (!stack.isEmpty() && stack.peekLast() == c) {
stack.pollLast();
} else {
stack.addLast(c);
}
}
StringBuildersb = newStringBuilder();
while (!stack.isEmpty()) {
sb.append(stack.pollLast());
}
returnsb.reverse().toString();
}
}
}