forked from sknsht/HackerRank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
34 lines (31 loc) · 1.01 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
import java.util.*;
public class Solution {
public static boolean isBalanced(String str) {
// Must be even
if ((str.length() & 1) == 1)
return false;
else {
char[] brackets = str.toCharArray();
Stack<Character> s = new Stack<>();
for (char bracket : brackets)
switch (bracket) {
case '{': s.push('}'); break;
case '(': s.push(')'); break;
case '[': s.push(']'); break;
default:
if (s.empty() || bracket != s.peek())
return false;
s.pop();
}
return s.empty();
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
while (n-- > 0) {
String expression = in.next();
System.out.println((isBalanced(expression)) ? "YES" : "NO");
}
}
}