-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBalanced_Parentheses.cpp
More file actions
74 lines (63 loc) · 1.63 KB
/
Balanced_Parentheses.cpp
File metadata and controls
74 lines (63 loc) · 1.63 KB
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
73
74
//
// Created by Mayank Parasar on 2020-01-26.
//
/*
* The Balanced Parentheses Problem - Classic Stack Problem ("Valid Parentheses" on Leetcode)
* */
#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <stack>
using namespace std;
stack<char> round_bracket;
stack<char> curly_bracket;
stack<char> square_bracket;
bool balanced_parentheses(string str) {
for(auto i : str) {
// cout << i << " ";
if(i == '[') {
square_bracket.push(i);
} else if(i == '{') {
curly_bracket.push(i);
} else if(i == '(') {
round_bracket.push(i);
}
// Make sure before poping is size is 0; if yes, then return false right away
else if(i == ']') {
if(square_bracket.size() > 0)
square_bracket.pop();
else
return false;
}
else if(i == '}') {
if(curly_bracket.size() > 0)
curly_bracket.pop();
else
return false;
}
else if(i == ')') {
if(round_bracket.size() > 0)
round_bracket.pop();
else
return false;
}
}
// check here the size of stacks; if any of them is greater than 0 then return false
if( round_bracket.size() == 0 &&
curly_bracket.size() == 0 &&
square_bracket.size() == 0 ) {
return true;
}
else {
return false;
}
// return true;
}
int main() {
string str = "[({()})[]}";
string str1 = "[{()}]";
cout << boolalpha;
cout << balanced_parentheses(str1);
return 0;
}