-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy path20-valid-parentheses.cpp
36 lines (33 loc) · 1 KB
/
20-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
#include <stack>
class Solution {
public:
bool isOpening(const char& c) {
if (c == '(' || c == '[' || c == '{') return true;
return false;
}
bool isComplement(const char& a, const char& b) {
if (a == '(' && b == ')') return true;
if (a == '{' && b == '}') return true;
if (a == '[' && b == ']') return true;
return false;
}
bool isValid(string s) {
if (s.length() == 0) {
return true;
}
stack<char> bracketStack;
for (auto it = s.cbegin(); it != s.cend(); it++) {
if (isOpening(*it)) {
bracketStack.push(*it);
} else {
if (!bracketStack.empty() && isComplement(bracketStack.top(), *it)) {
bracketStack.pop();
} else {
return false;
}
}
}
if (bracketStack.empty()) return true;
return false;
}
};