Skip to content

Commit 1a84236

Browse files
solve sremove all adjacent duplicats in a string
1 parent d104b22 commit 1a84236

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -284,7 +284,7 @@
284284
| 1037 | [Valid Boomerang](https://leetcode.com/problems/valid-boomerang) | [![Java](assets/java.png)](src/ValidBoomerang.java) | |
285285
| 1042 | [Flower Planting with no Adjacent](https://leetcode.com/problems/flower-planting-with-no-adjacent) | | |
286286
| 1046 | [Last Stone Weight](https://leetcode.com/problems/last-stone-weight) | [![Java](assets/java.png)](src/LastStoneWeight.java) | |
287-
| 1047 | [Remove All adjacent Duplicates in String](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string) | | |
287+
| 1047 | [Remove All adjacent Duplicates in String](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string) | [![Java](assets/java.png)](src/RemoveAllAdjacentDuplicatesInAString.java) | |
288288
| 1051 | [Height Checker](https://leetcode.com/problems/height-checker) | | |
289289
| 1056 | [Confusing Number](https://leetcode.com/problems/confusing-number) | | |
290290
| 1064 | [Fixed Point](https://leetcode.com/problems/fixed-point) | | |
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import java.util.Stack;
2+
3+
public class RemoveAllAdjacentDuplicatesInAString {
4+
5+
public String removeDuplicates(String s) {
6+
final Stack<Character> stack = new Stack<>();
7+
int k, count = 0;
8+
stack.push(s.charAt(0));
9+
for (int index = 1 ; index < s.length() ; index = k + 1, count = 0) {
10+
for (k = index ; k + 1 < s.length() && s.charAt(k + 1) == s.charAt(k) ; k++);
11+
if (!stack.isEmpty() && stack.peek() == s.charAt(k)) {
12+
for (count = 0 ; !stack.isEmpty() && stack.peek() == s.charAt(k) ; count++) {
13+
stack.pop();
14+
}
15+
}
16+
if (((k - index + 1 + count) & 1) == 1) stack.push(s.charAt(k));
17+
}
18+
StringBuilder result = getCharactersFrom(stack);
19+
return result.reverse().toString();
20+
}
21+
22+
private StringBuilder getCharactersFrom(Stack<Character> stack) {
23+
StringBuilder result = new StringBuilder();
24+
while (!stack.isEmpty()) {
25+
result.append(stack.pop());
26+
}
27+
return result;
28+
}
29+
}

0 commit comments

Comments
 (0)