forked from TECHOUS/DSKaKhel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbalancedParanthesis.cpp
More file actions
128 lines (118 loc) · 2.13 KB
/
balancedParanthesis.cpp
File metadata and controls
128 lines (118 loc) · 2.13 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
bool isempty();
/*=======> IMPLEMENTATION OF STACK <=======*/
static int top = -1; //storing top of a stack
char *stack; //dynamic stack
/*===============> ISEMPTY <===============*/
//returns boolean whether the stack is empty or not
bool isempty()
{
return top==-1;
}
/*================> PUSH <=================*/
void push(char value)
{
stack[++top] = value;
}
/*================> POP <==================*/
void pop()
{
if(isempty())
{
cout << "UNDERFLOW" << endl;
exit(0);
}
stack[top]=0;
top--;
}
/*================> PEEK <=================*/
//return the top element of the stack
char peek()
{
return stack[top];
}
/*==============> print the stack <=========*/
void display()
{
for(int i = 0 ; i <= top ; i++)
{
cout <<"| " <<stack[i]<<" |"<<endl;
}
if(top!=-1)
{
cout << "-----" << endl;
}
}
/*==================> SIZE <==============*/
int size()
{
return top+1;
}
/* ******************************************* */
//returns the bracket inversion
char invertBracket(char expr)
{
switch(expr)
{
case ']':
return '[';
case '}':
return '{';
case ')':
return '(';
default:
return ' ';
}
}
bool balancedParanthesis(string expression)
{
stack = new char[expression.size()]; //allocating dynamic stack
int i = 0;
while(expression[i] != '\0')
{
if(expression[i] == '[' || expression[i]=='{' || expression[i]== '(')
{
push(expression[i]);
}
else if(expression[i]==']' || expression[i]=='}' || expression[i]==')')
{
if(isempty())
{
return false;
}
//check top
if(invertBracket(expression[i])==peek()) //if bracket is same as the top element of the stack
{
pop();
}
}
i++;
}
if(isempty())
{
delete [] stack;
return true;
}
else
{
delete [] stack;
return false;
}
}
int main()
{
int ans;
string str;
getline(cin,str);
if(balancedParanthesis(str))
{
cout << "BRACKETS ARE BALANCED" << endl;
}
else
{
cout << "BRACKETS NOT BALANCED" << endl;
}
}