-
Notifications
You must be signed in to change notification settings - Fork 19
/
ParenthesisChecker.java
40 lines (35 loc) · 1.08 KB
/
ParenthesisChecker.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
import java.util.*;
import java.lang.*;
import java.io.*;
//http://practice.geeksforgeeks.org/problems/parenthesis-checker/0
class ParenthesisChecker {
public static void main (String[] args) {
ParenthesisChecker pc = new ParenthesisChecker();
Scanner in = new Scanner(System.in);
int testcases = in.nextInt();
while (--testcases >= 0) {
String str = in.next();
System.out.println(pc.isBalanced(str) ? "balanced" : "not balanced");
}
}
public boolean isBalanced(String s) {
Stack<Character> stack = new Stack<>();
char[] sArr = s.toCharArray();
for (int i = 0; i < sArr.length; i++) {
if (stack.empty()) {
stack.push(sArr[i]);
} else {
if (sArr[i] == ')' && stack.peek() == '(') {
stack.pop();
} else if (sArr[i] == '}' && stack.peek() == '{') {
stack.pop();
} else if (sArr[i] == ']' && stack.peek() == '[') {
stack.pop();
} else if (sArr[i] == '(' || sArr[i] == '[' || sArr[i] == '{' || sArr[i] == ')' || sArr[i] == '}' || sArr[i] == ']') {
stack.push(sArr[i]);
}
}
}
return stack.empty();
}
}