题目
解法:stack
繁琐的写法
class Solution {
public:
bool isValid(string s) {
if(s.size() % 2 != 0) return false;
stack<char> st;
for(auto c:s){
if(c == '(' || c == '[' || c == '{'){
st.push(c);
}else if(c == ')'){
if(st.empty() || st.top() != '(') return false;
st.pop();
}else if(c == ']'){
if(st.empty() || st.top() != '[') return false;
st.pop();
}else if(c == '}'){
if(st.empty() || st.top() != '{') return false;
st.pop();
}
}
if(!st.empty()) return false;
return true;
}
};
简单的写法:
class Solution {
public:
bool isValid(string s) {
if(s.size() % 2 != 0) return false;
stack<char> st;
unordered_map<char,char> pairs;
pairs[')'] = '(';
pairs[']'] = '[';
pairs['}'] = '{';
for (auto c : s){
if(pairs.find(c) == pairs.end()){
st.push(c);
}else{
if(st.empty() || pairs[c] != st.top()) return false;
st.pop();
}
}
if(st.empty()) return true;
return false;
}
};