-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathParenthesisChecker.java
93 lines (84 loc) · 2.25 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
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*Given an expression string exp. Examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp.
For example, the program should print 'balanced' for exp = “[()]{}{[()()]()}” and 'not balanced' for exp = “[(])”
Input:
The first line of input contains an integer T denoting the number of test cases. Each test case consists of a string of expression, in a separate line.
Output:
Print 'balanced' without quotes if the pair of parenthesis is balanced else print 'not balanced' in a separate line.
Constraints:
1 ≤ T ≤ 100
1 ≤ |s| ≤ 105
Example:
Input:
3
{([])}
()
([]
Output:
balanced
balanced
not balanced*/
import java.util.*;
import java.io.*;
class ParenthesisChecker {
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
sc.nextLine();
while(n-->0)
{
boolean flag=true;
String str=sc.nextLine();
Stack<Character> stk=new Stack<>();
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)=='('||str.charAt(i)=='{'||str.charAt(i)=='[')
{
stk.push(str.charAt(i));
}
else if(stk.empty()&&(str.charAt(i)==')'||str.charAt(i)=='}'||str.charAt(i)==']'))
{
flag=false;
break;
}
else if(!stk.empty()&&str.charAt(i)==')')
{
if(stk.peek()=='(')
stk.pop();
else
{
flag=false;
break;
}
}
else if(!stk.empty()&&str.charAt(i)==']')
{
if(stk.peek()=='[')
stk.pop();
else
{
flag=false;
break;
}
}
else if(!stk.empty()&&str.charAt(i)=='}')
{
if(stk.peek()=='{')
stk.pop();
else
{
flag=false;
break;
}
}
}
if(flag==true&&stk.empty())
{
System.out.println("balanced");
}
else
{
System.out.println("not balanced");
}
}
}
}