-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBalanceBrackets.cpp
63 lines (53 loc) · 1.32 KB
/
BalanceBrackets.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
/* https://www.hackerrank.com/challenges/balanced-brackets/problem
#stack #implementation
*/
// Solution worst O(N) - n: length of string input.
#include<iostream>
#include<stack>
using namespace std;
// check character is closing brackets ?
bool checkEndCharacter(char input, char &target) {
target = ' ';
if (input == ')')
target = '(';
else if (input == ']')
target = '[';
else if (input == '}')
target = '{';
if (target == ' ')
return false;
return true;
}
// Idea: if s[i] is closing bracket,
// check the previous element is corrosponding opening bracket?
bool isBalancedBrackets(string s) {
char openChar = ' ';
stack<char> st;
bool balanceFlg = true;
for(int i = 0; i < s.length(); ++i)
{
if(!checkEndCharacter(s[i], openChar)){
st.push(s[i]);
}
else {
if (st.top() != openChar) {
balanceFlg = false;
break;
} else {
st.pop();
}
}
}
if(!st.empty())
balanceFlg = false;
return balanceFlg;
}
//test
int main() {
string s = "([)]";
if(isBalancedBrackets(s))
cout << "TRUE"<<endl;
else
cout << "FALSE"<<endl;
return 0;
}