-
Notifications
You must be signed in to change notification settings - Fork 0
/
valid_parentheses.cpp
62 lines (49 loc) · 1.33 KB
/
valid_parentheses.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
/*
Given a string containing just the characters '(', ')', '{', '}',
'[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}"
are all valid but "(]" and "([)]" are not.
*/
#include <iostream>
#include <cassert>
#include <stack>
using namespace std;
bool opening_bracket(char c) {
return (c == '(' || c == '{' || c == '[');
}
char matching_bracket(char c) {
if(c == ')') return '(';
if(c == '}') return '{';
if(c == ']') return '[';
}
bool is_valid(string s) {
//uneven string can't be valid
if(s.length() % 2)
return false;
stack<char> brackets;
for(int i = 0; i < s.length(); i++) {
if(opening_bracket(s[i]))
brackets.push(s[i]);
else {
if(brackets.empty())
return false;
char top = brackets.top();
brackets.pop();
if(matching_bracket(s[i]) != top)
return false;
}
}
//brackets left over
if(brackets.size())
return false;
return true;
}
int main() {
assert(is_valid("()") == true);
assert(is_valid("()[]{}") == true);
assert(is_valid("(]") == false);
assert(is_valid("([)]") == false);
assert(is_valid("{{{{}}") == false);
assert(is_valid("") == true);
cout << "Success!" << endl;
}