-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBracketBalancer.java
More file actions
32 lines (26 loc) · 1.01 KB
/
Copy pathBracketBalancer.java
File metadata and controls
32 lines (26 loc) · 1.01 KB
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
import java.util.Stack;
public class BracketBalancer {
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) {
Stack<Character> stack = new Stack<>();
for (char ch : expression.toCharArray()) {
if (ch == '{' || ch == '(' || ch == '[') {
stack.push(ch);
} else if (ch == '}' || ch == ')' || ch == ']') {
if (stack.isEmpty()) return false;
char last = stack.pop();
if (!isPairValid(last, ch)) {
return false;
}
}
}
return stack.isEmpty();
}
private static boolean isPairValid(char open, char close) {
return (open == '{' && close == '}') || (open == '(' && close == ')') || (open == '[' && close == ']');
}
}