-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRemoveDuplicatesInString.java
30 lines (26 loc) · 1.05 KB
/
RemoveDuplicatesInString.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
package solutions;
// [Problem] https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string
class RemoveDuplicatesInString {
// StringBuilder as Stack
// O(n) time, O(n) space
public String removeDuplicates(String input) {
StringBuilder deduplicatedString = new StringBuilder();
for (char letter : input.toCharArray()) {
int strLength = deduplicatedString.length();
if (strLength > 0 && deduplicatedString.charAt(strLength - 1) == letter) {
deduplicatedString.deleteCharAt(strLength - 1);
} else {
deduplicatedString.append(letter);
}
}
return deduplicatedString.toString();
}
// Test
public static void main(String[] args) {
RemoveDuplicatesInString solution = new RemoveDuplicatesInString();
String input = "abbaca";
String expectedOutput = "ca";
String actualOutput = solution.removeDuplicates(input);
System.out.println("Test passed? " + expectedOutput.equals(actualOutput));
}
}