-
Notifications
You must be signed in to change notification settings - Fork 184
/
Copy pathSolution.java
39 lines (34 loc) · 1.08 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
37
38
39
import java.util.*;
class Solution {
private static boolean isBalanced(String expression) {
if ((expression.length() & 1) == 1)
return false;
char[] brackets = expression.toCharArray();
Stack<Character> stack = new Stack<>();
for (char bracket : brackets)
switch (bracket) {
case '{':
stack.push('}');
break;
case '(':
stack.push(')');
break;
case '[':
stack.push(']');
break;
default:
if (stack.empty() || bracket != stack.peek())
return false;
stack.pop();
}
return stack.empty();
}
public static void main(String[] argh) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String expression = sc.next();
System.out.println(isBalanced(expression) ? "true" : "false");
}
sc.close();
}
}