Skip to content

Commit c82dbaa

Browse files
committed
Checking Balanced Parenthesis
1 parent 40a0de2 commit c82dbaa

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

Diff for: balanced_parenthesis_check.cpp

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
// function to check if parenthesis are balanced
5+
bool areParanthesisBalanced(string expr)
6+
{
7+
stack<char> s;
8+
char x;
9+
10+
// Traversing the Expression
11+
for (int i=0; i<expr.length(); i++)
12+
{
13+
if (expr[i]=='('||expr[i]=='['||expr[i]=='{')
14+
{
15+
// Push the element in the stack
16+
s.push(expr[i]);
17+
continue;
18+
}
19+
20+
// IF current current character is not opening
21+
// bracket, then it must be closing. So stack
22+
// cannot be empty at this point.
23+
if (s.empty())
24+
return false;
25+
26+
switch (expr[i])
27+
{
28+
case ')':
29+
30+
// Store the top element in a
31+
x = s.top();
32+
s.pop();
33+
if (x=='{' || x=='[')
34+
return false;
35+
break;
36+
37+
case '}':
38+
39+
// Store the top element in b
40+
x = s.top();
41+
s.pop();
42+
if (x=='(' || x=='[')
43+
return false;
44+
break;
45+
46+
case ']':
47+
48+
// Store the top element in c
49+
x = s.top();
50+
s.pop();
51+
if (x =='(' || x == '{')
52+
return false;
53+
break;
54+
}
55+
}
56+
57+
// Check Empty Stack
58+
return (s.empty());
59+
}
60+
int main()
61+
{
62+
// string expr = "{()}[]";
63+
string expr;
64+
cout<<"Enter a String: ";
65+
cin>>expr;
66+
// cout<<s;
67+
if(areParanthesisBalanced(expr))
68+
cout << "Balanced";
69+
else
70+
cout << "Not Balanced";
71+
return 0;
72+
}

0 commit comments

Comments
 (0)