-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBalanced_Brackets.java
78 lines (74 loc) · 1.46 KB
/
Balanced_Brackets.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
import java.io.*;
import java.util.*;
public class Balanced_Brackets
{
static class Stack
{
int top=-1;
char items[]=new char[100];
void push(char x)
{
if(top==99)
{
System.out.println("Stack is full");
}
else
items[++top]=x;
}
char pop(){
if(top==-1){
System.out.println("Stack is empty");
return '\0';
}
else
{
char element = items[top];
top--;
return element;
}
}
boolean isEmpty(){
return (top==-1)?true:false;
}
}
static boolean isMatchingPair(char c1, char c2){
if(c1=='(' && c2==')'){
return true;}
else if(c1=='{' && c2=='}'){
return true;}
else if(c1=='[' && c2==']'){
return true;}
else
return false;
}
static boolean Balanced(char exp[])
{
Stack st = new Stack();
for(int i=0;i<exp.length;i++){
if(exp[i]=='{' || exp[i]=='(' || exp[i]=='['){
st.push(exp[i]);
}
if(exp[i]=='}' || exp[i]==')' || exp[i]==']'){
if(st.isEmpty()){ //checking whether the stack is Empty
return false;
}
else if(!isMatchingPair(st.pop(), exp[i])){
return false;
}
}
}
if(st.isEmpty())
return true; /*balanced*/
else{
return false;
}
}
public static void main(String[] args)
{
char exp[] = {'{','(',')','}','[',']', '{'};
if (Balanced(exp))
System.out.println("Balanced ");
else
System.out.println("Not Balanced ");
}
}