-
Notifications
You must be signed in to change notification settings - Fork 54
/
Balanced_Paranthesis.cpp
65 lines (58 loc) · 1.34 KB
/
Balanced_Paranthesis.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
#include <bits/stdc++.h>
using namespace std;
// function to check if brackets are balanced
bool is_balanced(string exp)
{
stack<char> s;
char x;
// Traversing the Expression
for (int i = 0; i < exp.length(); i++)
{
if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[')
{
// Push the element in the stack
s.push(exp[i]);
continue;
}
// IF current current character is not opening
// bracket, then it must be closing. So stack
// cannot be empty at this point.
if (s.empty())
return false;
switch (exp[i])
{
case ')':
x = s.top();
s.pop();
if (x == '{' || x == '[')
return false;
break;
case '}':
x = s.top();
s.pop();
if (x == '(' || x == '[')
return false;
break;
case ']':
x = s.top();
s.pop();
if (x == '(' || x == '{')
return false;
break;
default:
break;
}
}
return (s.empty());
}
// driver code
int main()
{
string str;
cout << "Enter the expression: ";
cin >> str;
if (is_balanced(str))
cout << "\nBALANCED";
else
cout << "\nNOT BALANCED";
}