-
Notifications
You must be signed in to change notification settings - Fork 17
/
BalancedParenthesis.java
37 lines (36 loc) · 1.15 KB
/
BalancedParenthesis.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
package SummerTrainingGFG.Stack;
import java.util.Stack;
/**
* @author Vishal Singh
*/
public class BalancedParenthesis {
static boolean check(char a,char b){
return (a=='{' && b == '}')||(a=='[' && b == ']')||(a=='(' && b == ')');
}
static boolean isBalancedParenthesis(String str){
Stack<Character> stack = new Stack<>();
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i) == '{' || str.charAt(i) == '[' || str.charAt(i) == '('){
stack.push(str.charAt(i));
}
else{
if(stack.isEmpty()){
return false;
}
else if(check(str.charAt(i),stack.peek())){
return false;
}
else{
stack.pop();
}
}
}
return stack.empty();
}
public static void main(String[] args) {
String parenthesis = "{[([{}])]}"; // TRUE
String parenthesis1 = "{[}]}"; // FALSE
System.out.println(isBalancedParenthesis(parenthesis));
System.out.println(isBalancedParenthesis(parenthesis1));
}
}