Leetcode20
1.问题描述
2.解决方案
解法一:栈
主要是两处判断要想到,对应两种特殊情况,第一处是如果有 “}}” 这种情况,第二处对应遍历完栈还没空的情况
if(st.empty()== true) return false;
if(st.empty()== false) return false;
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(int i=0;i<s.length();i++){
if(s[i]=='('||s[i]=='['||s[i]=='{') st.push(s[i]);
else{
if(st.empty()== true) return false;
//bool a=s[i]==')'&&st.top()=='(';
//bool b=s[i]==']'&&st.top()=='[';
//bool c=s[i]=='}'&&st.top()=='{';
if((s[i]==')'&&st.top()=='(')||(s[i]==']'&&st.top()=='[')||(s[i]=='}'&&st.top()=='{')) st.pop();
else return false;
}
}
if(st.empty()== false) return false;
return true;
}
};
解法二:栈(官方优化)
优化点:
1.如果是奇数个直接return false
if (n % 2 == 1) {
return false;
}
2.使用了unordered_map更加快速匹配左右括号
3.增强for,还可以很优雅,自己经常忘记用
for (char ch: s)
class Solution {
public:
bool isValid(string s) {
int n = s.size();
if (n % 2 == 1) {
return false;
}
unordered_map<char, char> pairs = {
{')', '('},
{']', '['},
{'}', '{'}
};
stack<char> stk;
for (char ch: s) {
if (pairs.count(ch)) {
if (stk.empty() || stk.top() != pairs[ch]) {
return false;
}
stk.pop();
}
else {
stk.push(ch);
}
}
return stk.empty();
}
};