-
-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathBalancedBrackets.java
35 lines (32 loc) · 997 Bytes
/
BalancedBrackets.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
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static String isBalanced(String s) {
Stack<Character> stack = new Stack<>();
int i = 0;
for(Character c : s.toCharArray()){
if(c=='(' || c=='[' || c=='{'){
stack.push(c);
} else if(stack.isEmpty()){
break;
} else if((c==')' && stack.peek()=='(') || (c==']' && stack.peek()=='[') || (c=='}' && stack.peek()=='{')){
stack.pop();
}
i++;
}
return (i==s.length() && stack.isEmpty()) ? "YES" : "NO";
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
String s = in.next();
String result = isBalanced(s);
System.out.println(result);
}
in.close();
}
}