Skip to content

Commit 3d25ef5

Browse files
Create BalancedParenthesis.cpp
1 parent 7f33a43 commit 3d25ef5

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

C++/BalancedParenthesis.cpp

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
bool areBracketsBalanced (string expr)
5+
{
6+
7+
stack < char >s;
8+
char x;
9+
10+
11+
// Traversing the Expression
12+
for (int i = 0; i < expr.length (); i++)
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+
24+
if (s.empty ())
25+
return false;
26+
27+
switch (expr[i])
28+
{
29+
30+
case ')': // Store the top element in a
31+
x = s.top ();
32+
s.pop ();
33+
34+
if (x == '{' || x == '[')
35+
return false;
36+
37+
break;
38+
39+
case '}': // Store the top element in b
40+
x = s.top ();
41+
s.pop ();
42+
if (x == '(' || x == '[')
43+
return false;
44+
break;
45+
case ']': x = s.top ();
46+
s.pop ();
47+
if (x == '(' || x == '{')
48+
return false;
49+
break;
50+
}
51+
}
52+
return (s.empty ());
53+
}
54+
// Driver code
55+
int main ()
56+
{
57+
string expr = "{()}[]";
58+
// Function call
59+
if (areBracketsBalanced (expr))
60+
cout << "Balanced";
61+
else
62+
cout << "Not Balanced";
63+
return 0;
64+
}

0 commit comments

Comments
 (0)