forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Check_for_balanced_parenthesis.cpp
72 lines (59 loc) · 1.35 KB
/
Check_for_balanced_parenthesis.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
/*
Check for balanced parenthesis
==============================
Given an expression containing parenthesis, check if it is well-formed or balanced.
Example of balanced parenthesis are: (), ((())), (a+b), (a/b)*(b/a)
Application: Stack data structure
Time Complexity: O(n)
Space Complexity: O(n)
*/
#include<iostream>
#include <stack>
using namespace std;
bool isBalanced(string str) {
// Size of the string
int n = str.size();
// Stack to store open parenthesis
stack<int> s;
// Open parenthesis -> 1
// Loop through characters in the string
for (int i = 0; i < n; i++) {
// Open parenthesis is always pushed into the stack
if (str[i] == '(') {
s.push(1);
} else if (str[i] == ')') {
// Closed parenthesis encountered must be balanced by an open parenthesis already
// present in the stack
if (!s.empty()) {
// Stack contains open parenthesis, one of which has been balanced
// Pop one parenthesis out
s.pop();
} else {
// Stack contains no open parenthesis. So closed parenthesis cannot be balanced
return 0;
}
}
}
// Check if we have open parenthesis remaining
if (s.size()) {
return 0;
} else {
return 1;
}
}
int main() {
// Input the string
string str; cin >> str;
if (isBalanced(str)) cout << "Yes";
else cout << "No";
}
/*
Input:
((a+b)+(c-d+f))
Output:
Yes
Input:
((a+b)+(c-d+f)))
Output:
No
*/