-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path20.cpp
44 lines (36 loc) · 1.03 KB
/
20.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
// 20. Valid Parentheses - https://leetcode.com/problems/valid-parentheses
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isValid(string s) {
string open_parentheses = "{[(";
unordered_map<char, char> get_open_parenthesis_for {
{'}', '{'},
{']', '['},
{')', '('},
};
stack<char> st;
for (char ch : s) {
if (open_parentheses.find(ch) != string::npos) {
st.push(ch);
} else {
if (!st.empty() && st.top() == get_open_parenthesis_for[ch]) {
st.pop();
} else {
return false;
}
}
}
return st.empty();
}
};
int main() {
ios::sync_with_stdio(false);
Solution solution;
assert(solution.isValid("()") == true);
assert(solution.isValid("()[]{}") == true);
assert(solution.isValid("()[)]{}") == false);
assert(solution.isValid("([)]") == false);
return 0;
}