-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Solution.java
36 lines (30 loc) · 1.05 KB
/
Solution.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
// github.com/RodneyShag
import java.util.Scanner;
import java.util.Stack;
// Time Complexity: O(n)
// Space Complexity: O(n)
// Can alternatively use an ArrayDeque instead of a Stack. Just make sure to iterate
// through it properly since iteration order is opposite that of a Stack.
String superReducedString(String str) {
/* Iterate through String, creating final result in a Stack */
Stack<Character> stack = new Stack();
for (int i = 0; i < str.length(); i++) {
Character ch = str.charAt(i);
if (!stack.isEmpty() && ch == stack.peek()) {
stack.pop(); // since String has 2 adjacent equal characters
} else {
stack.push(ch);
}
}
/* Return final result */
if (stack.isEmpty()) {
return "Empty String";
} else {
StringBuffer sb = new StringBuffer();
for (char ch : stack) {
sb.append(ch);
}
return sb.toString();
}
}
// Discuss on HackerRank: https://www.hackerrank.com/challenges/reduced-string/forum/comments/263979