-
Notifications
You must be signed in to change notification settings - Fork 0
/
BracketBalancerTreeSet.java
51 lines (42 loc) · 1.57 KB
/
BracketBalancerTreeSet.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.util.TreeSet;
public class BracketBalancerTreeSet {
public static void main(String[] args) {
System.out.println(isBalanced("{{(){}}}")); // true
System.out.println(isBalanced("}{}{")); // false
System.out.println(isBalanced("({})")); // true
}
public static boolean isBalanced(String expression) {
TreeSet<Bracket> simulatedStack = new TreeSet<>();
int order = 0;
for (char ch : expression.toCharArray()) {
if (ch == '{' || ch == '(' || ch == '[') {
simulatedStack.add(new Bracket(ch, order));
order++;
} else if (ch == '}' || ch == ')' || ch == ']') {
if (simulatedStack.isEmpty()) return false;
Bracket last = simulatedStack.last();
simulatedStack.remove(last);
if (!isPairValid(last.bracket, ch)) {
return false;
}
order--;
}
}
return simulatedStack.isEmpty();
}
private static boolean isPairValid(char open, char close) {
return (open == '{' && close == '}') || (open == '(' && close == ')') || (open == '[' && close == ']');
}
private static class Bracket implements Comparable<Bracket> {
char bracket;
int order;
Bracket(char bracket, int order) {
this.bracket = bracket;
this.order = order;
}
@Override
public int compareTo(Bracket other) {
return Integer.compare(this.order, other.order);
}
}
}