-
Notifications
You must be signed in to change notification settings - Fork 0
/
BracketStack.java
60 lines (57 loc) · 1.89 KB
/
BracketStack.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
52
53
54
55
56
57
58
59
60
import java.util.*;
public class BracketStack {
public static boolean isBalanced(String expression) {
Stack<Character> bs = new Stack<Character>();
char c;
for(int i=0;i<expression.length();i++){
c = expression.charAt(i);
//System.out.println(c);
switch(c){
case '[':
case '{':
case '(':
bs.push(c);
break;
case ']':
//d = bs.pop();
//System.out.println("Popped:"+d);
if(bs.isEmpty() || !bs.pop().toString().equals("["))
return false;
break;
case '}':
//d = bs.pop();
//System.out.println("Popped:"+d);
if(bs.isEmpty() || !bs.pop().toString().equals("{"))
return false;
break;
case ')':
//d = bs.pop();
//System.out.println("Popped:"+d);
if(bs.isEmpty() || !bs.pop().toString().equals("("))
return false;
break;
default:
return false;
}
}
if(!bs.empty())
{
//System.out.println("still looking and not empty");
return false;
}
else
return true;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++) {
String expression = in.next();
boolean answer = isBalanced(expression);
if(answer)
System.out.println("YES");
else System.out.println("NO");
}
in.close();
}
}