-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBalancedParanthesis.java
70 lines (59 loc) · 1.39 KB
/
BalancedParanthesis.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
import java.util.*;
class Stack2{
char stack[]=new char[200];
int top=0;
public void push(char c) {
stack[top]=c;
top++;
}
public void pop() {
top--;
stack[top]='\u0000';
}
public char Top() {
char v=stack[top-1];
return v;
}
public boolean empty() {
if(stack[0]=='\u0000')
return true;
else
return false;
}
}
public class BalancedParanthesis {
Stack2 s=new Stack2();
public boolean arepair(char opening , char closing) {
if(opening =='('&& closing==')')
return true;
else if (opening=='{'&& closing=='}')
return true;
else if (opening=='['&& closing==']')
return true;
else
return false;
}
public boolean balancedparanthesis(String exp ) {
for(int i=0;i<exp.length();i++) {
if(exp.charAt(i)=='('||exp.charAt(i)=='{'||exp.charAt(i)=='[')
s.push(exp.charAt(i));
else if(exp.charAt(i)==')'||exp.charAt(i)=='}'||exp.charAt(i)==']')
{
if(s.empty()||!arepair(s.Top(),exp.charAt(i))) {
return false;}
else
s.pop();
}
}
return s.empty()?true:false;
}
public static void main(String[] args) throws NullPointerException {
Scanner sc=new Scanner(System.in);
String expression=sc.next();
BalancedParanthesis bp=new BalancedParanthesis();
if(bp.balancedparanthesis(expression)) {
System.out.println("balanced");
}
else System.out.println("not balanced");
}
}