-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathMakeTheStringGreat.java
More file actions
28 lines (24 loc) · 914 Bytes
/
MakeTheStringGreat.java
File metadata and controls
28 lines (24 loc) · 914 Bytes
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
// https://leetcode.com/problems/make-the-string-great
// T: O(N)
// S: O(N)
import java.util.Stack;
public class MakeTheStringGreat {
public String makeGood(String s) {
final Stack<Character> characters = new Stack<>();
for (int index = 0 ; index < s.length() ; index++) {
char c = s.charAt(index);
if (!characters.isEmpty() && c == inverse(characters.peek())) {
characters.pop();
} else characters.push(c);
}
return toStringBuilder(characters).reverse().toString();
}
private StringBuilder toStringBuilder(Stack<Character> stack) {
StringBuilder result = new StringBuilder();
while (!stack.isEmpty()) result.append(stack.pop());
return result;
}
private char inverse(char c) {
return Character.isUpperCase(c) ? Character.toLowerCase(c) : Character.toUpperCase(c);
}
}