Wednesday, March 10, 2021, the weather is fine [Do not lament the past, do not waste the present, do not fear the future]
Contents of this article
1. Introduction
2. Problem solution (the magical effect of the stack)
The idea of this question is not difficult: it is easier to solve by using the first-in-first-out feature of the stack. The problem lies in the realization of the program, and there is a relatively concise way of writing.
Conventional writing:
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(const char &c:s){
if(st.empty()) {
if(c==')'||c=='}'||c==']') return false;
st.push(c);
continue;
}
char tmp = st.top();
bool flg = false;
switch(c){
case ')':flg = tmp=='('?true:false;break;
case '}':flg = tmp=='{'?true:false;break;
case ']':flg = tmp=='['?true:false;break;
}
flg?st.pop():st.push(c);
}
return st.empty();
}
};
Concise writing:
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(const char &c:s){
// 如果是左括号,栈中加入右括号
if(c=='(') st.push(')');
else if(c=='{') st.push('}');
else if(c=='[') st.push(']');
// 如果不为空且与栈顶元素相等,说明凑成一对括号了,弹出栈顶元素
else if(!st.empty()&&c==st.top()) st.pop();
// 否则说明无法凑成一对括号,返回false
else return false;
}
return st.empty();
}
};
references
https://leetcode-cn.com/problems/valid-parentheses/comments/