-
Notifications
You must be signed in to change notification settings - Fork 51
/
BalancedParenthesis.cpp
65 lines (50 loc) · 1.13 KB
/
BalancedParenthesis.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
// C++ program for the above approach.
#include <bits/stdc++.h>
using namespace std;
// Function to check
// if parentheses are balanced
bool isBalanced(string exp)
{
// Initialising Variables
bool flag = true;
int count = 0;
// Traversing the Expression
for (int i = 0; i < exp.length(); i++) {
if (exp[i] == '(') {
count++;
}
else {
// It is a closing parenthesis
count--;
}
if (count < 0) {
// This means there are
// more Closing parenthesis
// than opening ones
flag = false;
break;
}
}
// If count is not zero,
// It means there are
// more opening parenthesis
if (count != 0) {
flag = false;
}
return flag;
}
// Driver code
int main()
{
string exp1 = "((()))()()";
if (isBalanced(exp1))
cout << "Balanced \n";
else
cout << "Not Balanced \n";
string exp2 = "())((())";
if (isBalanced(exp2))
cout << "Balanced \n";
else
cout << "Not Balanced \n";
return 0;
}