Leetcode20
1.问题描述
2.解决方案
解法一:通过分析不匹配情况进行代码实现
class Solution {
public:
bool isValid(string s) {
stack<int> st;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(') st.push(')');
else if (s[i] == '{') st.push('}');
else if (s[i] == '[') st.push(']');
// 第三种情况:遍历字符串匹配的过程中,栈已经为空了,没有匹配的字符了,说明右括号没有找到对应的左括号 return false
// 第二种情况:遍历字符串匹配的过程中,发现栈里没有我们要匹配的字符。所以return false
else if (st.empty() || st.top() != s[i]) return false;
else st.pop(); // st.top() 与 s[i]相等,栈弹出元素
}
// 第一种情况:此时我们已经遍历完了字符串,但是栈不为空,说明有相应的左括号没有右括号来匹配,所以return false,否则就return true
return st.empty();
}
};
解法二:栈
主要是两处判断要想到,对应两种特殊情况
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();
}
};