-
Notifications
You must be signed in to change notification settings - Fork 0
/
20-ValidParentheses.cpp
52 lines (46 loc) · 1.49 KB
/
20-ValidParentheses.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
/*=============================================================================
# FileName: 20-ValidParentheses.cpp
# Desc: AC, 0ms
# Author: Jian Huang
# Email: [email protected]
# HomePage: https://cn.linkedin.com/in/huangjian1993
# Version: 0.0.1
# LastChange: 2015-08-02 20:57:46
# History:
=============================================================================*/
#include <leetcode.h>
class Solution {
public:
bool isLeft(char c) {
return c == '[' || c == '{' || c == '(';
}
bool isMatch(char c1, char c2) {
return (c1 == '[' && c2 == ']') || (c1 == '{' && c2 == '}') || (c1 == '(' && c2 == ')');
}
bool isValid(string s) {
stack<char> myStack;
int len = s.length();
for (int i = 0; i < len; i ++) {
char c = s[i];
if (isLeft(c)) {
myStack.push(c);
} else {
if (myStack.empty()) {
return false;
} else {
char top = myStack.top();
if (!isMatch(top, c)) {
return false;
}
myStack.pop();
}
}
}
return myStack.empty() ? true : false;
}
};
int main() {
Solution solution;
cout << solution.isValid("{[)]") << endl;
return 0;
}