-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbalancedpara.java
53 lines (42 loc) · 1.03 KB
/
balancedpara.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
//to check if a the brackets are balanced or not.
//i.e all the normal conditios for paranthesis to be balanced
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class balancedpara{
public static char[][] TOKENS={{'{','}'},{'[',']'},{'(',')'}};
public static boolean isOpenTerm(char c){
for(char[] array:TOKENS){
if(array[0]==c)
return true;
}
return false;
}
public static boolean matches(char openTerm,char closeTerm){
for(char[] array:TOKENS){
if(array[0]==openTerm)
return array[1]==closeTerm;
}
return false;
}
public static boolean isBalanced(String expression){
Stack<Character> stack= new Stack<Character>();
for(char c:expression.toCharArray()){
if(isOpenTerm(c)){
stack.push(c);
} else{
if(stack.isEmpty()||!matches(stack.pop(),c)){
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args){
String s="{((([{}])))}";
boolean ans=isBalanced(s);
System.out.println(ans);
}
}