-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
66 lines (56 loc) · 1.68 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package org.gradle;
import java.util.*;
public class Solution {
private static Stack<Character> stack=new Stack<>();
private static String SAMPLE="{[()]}";
public static void main(String[] args) {
List<String> inputs=new ArrayList<>();
Scanner in = new Scanner(System.in);
try{
int t = in.nextInt();
if(!(1<=t && t<=1000)){
throw new IllegalArgumentException("Invalid no of strings");
}
for(int a0 = 0; a0 < t; a0++){
String input = in.next();
if(!(1<=input.length() && input.length()<=1000)){
throw new IllegalArgumentException("Invalid no of strings");
}
inputs.add(input);
}
for(String input:inputs){
checkBalanced(input);
}
}finally{
in.close();
}
}
private static void checkBalanced(String input){
stack.clear();
char[] charArray=input.toCharArray();
for(int index=0;index<charArray.length;index++){
char text=charArray[index];
if(!SAMPLE.contains(Character.toString(text))){
throw new IllegalArgumentException("Input can only contain brackets");
}
if(text=='{' || text=='[' || text=='('){
stack.push(text);
}else{
if(stack.empty()){
System.out.println("NO");
return;
}
char top=stack.pop();
if((top == '[' && text!=']') || (top == '{' && text!='}') || (top == '(' && text!=')')){
System.out.println("NO");
return;
}
}
}
if(stack.empty()){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}