-
Notifications
You must be signed in to change notification settings - Fork 0
/
Balanced_Parentheses_Checker.cpp
103 lines (93 loc) · 2.75 KB
/
Balanced_Parentheses_Checker.cpp
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
#include <iostream>
using namespace std;
#define MAX 100
/*---------------------------------------------------------------------------*/
typedef struct stack{
char elem[100];
int top;
};
/*---------------------------------------------------------------------------*/
void push(stack *s, char item){
if (s->top == MAX - 1){
cout << "stack full";
}
else{
s->top = s->top + 1;
s->elem[s->top] = item;
}
}
/*---------------------------------------------------------------------------*/
bool isempty(stack *s){
if (s->top == -1)
return true;
else
return false;
}
/*---------------------------------------------------------------------------*/
char pop(stack *s){
if (s->top == -1){
cout << "stack empty";
return -1;
}
else{
return s->elem[s->top--];
}
}
/*---------------------------------------------------------------------------*/
// function to check if brackets are balanced
bool areBracketsBalanced(string expr){
char x;
stack s;
s.top = -1;
// Traversing the Expression
for (int i = 0; i < expr.length(); i++){
if (expr[i] == '(' || expr[i] == '[' || expr[i] == '{'){
// Push the element in the stack
push(&s, expr[i]);
}
// IF current current character is not opening bracket, then it must be closing. So stack cannot be empty at this point.
if (isempty(&s))
return false;
switch (expr[i]){
case ')':
// Store the top element in a
x = pop(&s);
if (x == '{' || x == '[')
return false;
break;
case '}':
// Store the top element in b
x = pop(&s);
if (x == '(' || x == '[')
return false;
break;
case ']':
// Store the top element in c
x = pop(&s);
if (x == '(' || x == '{')
return false;
break;
}
}
// Check Empty Stack
return (isempty(&s));
}
/*---------------------------------------------------------------------------*/
// Driver code
int main(){
string expr;
cout << "Enter an expression : ";
cin >> expr;
// Function call
if (areBracketsBalanced(expr))
cout << "The Parentheses are Balanced in the given Expression \n";
else
cout << "The Parentheses are Not Balanced in the given Expression \n";
return 0;
}
/* Sample inputs :
{x^[(n(n+1))÷5n]/(2n+1)}
{x^[(n(n+1))÷5n])/(2n+1))
{x^[(n(n+1)]÷5n))/(2n+1})
*/
/*---------------------------------------------------------------------------*/