forked from cpselvis/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution020.cpp
More file actions
51 lines (48 loc) · 936 Bytes
/
solution020.cpp
File metadata and controls
51 lines (48 loc) · 936 Bytes
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
/**
* Valid Parentheses
* Stack
*
* cpselvis([email protected])
* August 19, 2016
*/
#include<iostream>
#include<stack>
#include<map>
using namespace std;
class Solution {
public:
bool isValid(string s) {
stack<char> st;
map<char, char> m = {{')', '('}, {']', '['}, {'}', '{'}};
for (auto ch : s)
{
auto it = m.find(ch);
if (it != m.end())
{
// If not find, then it's a closing parenthense.
if (st.empty() || it -> second != st.top())
{
return false;
}
else
{
st.pop();
}
}
else
{
// It's a opening parenthense.
st.push(ch);
}
}
return st.empty();
}
};
int main(int argc, char **argv)
{
Solution s;
cout << "() :" << s.isValid("()") << endl;
cout << "()[]{} :" << s.isValid("()[]{}") << endl;
cout << "(] :" << s.isValid("(]") << endl;
cout << "([)]" << s.isValid("([)]") << endl;
}