forked from srishilesh/Data-Structure-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1047_Remove_adjacent_duplicates
37 lines (33 loc) · 992 Bytes
/
1047_Remove_adjacent_duplicates
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
// https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/
// My solution
class Solution {
public String removeDuplicates(String S) {
Stack<Character> stack = new Stack<Character>();
char[] arr = S.toCharArray();
for (char ch : arr) {
if (!stack.isEmpty() && stack.peek() == ch) {
stack.pop();
}
else {
stack.push(ch);
}
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) {
sb.append(stack.pop());
}
sb.reverse();
return sb.toString();
}
}
// Other solution
public String removeDuplicates(String s) {
int i = 0, n = s.length();
char[] res = s.toCharArray();
for (int j = 0; j < n; ++j, ++i) {
res[i] = res[j];
if (i > 0 && res[i - 1] == res[i]) // count = 2
i -= 2;
}
return new String(res, 0, i);
}