-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBracketBalanceOptimized.java
More file actions
43 lines (36 loc) · 1.1 KB
/
Copy pathBracketBalanceOptimized.java
File metadata and controls
43 lines (36 loc) · 1.1 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
33
34
35
36
37
38
39
40
41
42
43
/*
This is an optimized code for the previous version of the same problem
*/
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class BracketBalanceOptimized {
public static boolean isBalanced(String expression) {
if ((expression.length() & 1) == 1) return false;
else{
Stack<Character> stk = new Stack();
for(char c : expression.toCharArray()){
switch(c){
case '(' : stk.push(')'); break;
case '[' : stk.push(']'); break;
case '{' : stk.push('}'); break;
default :
if(stk.isEmpty() || c!=stk.peek())
return false;
stk.pop();
}
}
return stk.isEmpty();
}
}
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();
System.out.println( (isBalanced(expression)) ? "YES" : "NO" );
}
}
}