leetcode-20-字符串题-有效的括号

题目

1.png

解法

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
class Solution {
public:
bool isValid(string s) {
if(s.empty()) return true;

stack<char> help;
for(auto x : s){
if(x == '(' || x == '[' || x == '{'){
help.push(x);
}else{
if(!help.empty()){
if(x == ')' && help.top() == '('){
help.pop();
}else if(x == ']' && help.top() == '['){
help.pop();
}else if(x == '}' && help.top() == '{'){
help.pop();
}else{
return false;
}
}else{
return false;
}
}
}

return help.empty() ? true : false;
}
};