-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathC4P1.java
More file actions
66 lines (56 loc) · 1.72 KB
/
C4P1.java
File metadata and controls
66 lines (56 loc) · 1.72 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//Check the balancing of the symbols
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Scanner;
import java.util.Set;
import java.util.Stack;
public class C4P1 {
// Push the open brackets into the stacks
// Pop the open brackets if the closed onces are the pairs of open brackets
// By the end the stack is empty
static Boolean isBalanced(String s) {
Stack<Character> stack = new Stack<Character>();
Set<Character> openBrackets = new HashSet<Character>();
openBrackets.add('(');
openBrackets.add('{');
openBrackets.add('[');
Set<Character> closedBrackets = new HashSet<Character>();
closedBrackets.add(')');
closedBrackets.add('}');
closedBrackets.add(']');
Hashtable<Character, Character> pairs = new Hashtable<Character, Character>();
pairs.put(')', '(');
pairs.put(']', '[');
pairs.put('}', '{');
char[] stringToCharArray = s.toCharArray();
for (int i = 0; i < stringToCharArray.length; i++) {
if(openBrackets.contains(stringToCharArray[i])) {
stack.push(stringToCharArray[i]);
}
else {
if(stack.isEmpty())
return false;
else {
char temp = stack.pop();
if(!(pairs.get(stringToCharArray[i]) == temp)) {
return false;
}
}
}
}
return stack.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 s = in.next();
boolean result = isBalanced(s);
if(result)
System.out.println("YES");
else
System.out.println("NO");
}
in.close();
}
}