Leetcode 20 Valid Parentheses stack的应用

时间:2023-03-08 19:20:30
Leetcode 20 Valid Parentheses stack的应用

判断括号是否合法

1.用stack存入左括号“([{”,遇到相应的右括号“)]}”就退栈

2.判断stack是否为空,可以判断是否合法

 class Solution {
public:
bool isValid(string s) {
stack<char> sc;
char in[] ="([{";
char out[] =")]}";
for(string::size_type i = ; i < s.size(); ++i){
for(int j = ; j < ; ++j){
if(in[j] == s[i]) sc.push(s[i]);
}
for(int j = ; j < ; ++j){
if(out[j] == s[i]){
if(sc.empty()) return false;
else if(sc.top() == in[j]) sc.pop();
else return false;
}
}
}
return sc.empty();
}
};