-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParenthiesesMatching.java
53 lines (51 loc) · 1 KB
/
ParenthiesesMatching.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
import java.util.*;
public class ParenthiesesMatching {
char stack[];
int top;
ParenthiesesMatching(int n){
stack=new char[n];
top=-1;
}
void push(char c) {
stack[++top]=c;
}
char pop() {
return stack[top--];
}
boolean check(String s) {
char a[]=s.toCharArray();
for(char i:a) {
if(i=='(' || i=='{' || i=='[')
push(i);
if(top==-1)
return false;
char x='\u0000';
switch(i) {
case ')':
x=pop();
if(x != '(')
return false;
break;
case '}':
x=pop();
if(x != '{')
return false;
break;
case ']':
x=pop();
if(x != '[')
return false;
}
}
return (top==-1);
}
public static void main(String args[]) {
System.out.println("Enter parentheses");
String s=new Scanner(System.in).next();
ParenthiesesMatching ob=new ParenthiesesMatching(s.length());
if(ob.check(s))
System.out.println("It is balanced");
else
System.out.println("It is not balanced");
}
}