20. 有效的括号
https://leetcode.cn/problems/valid-parentheses/
由于栈结构的特殊性,非常适合做对称匹配类的题目。
有三种不匹配的情况:
- 第一种情况,字符串里左方向的括号多余了 ,所以不匹配。
- 第二种情况,括号没有多余,但是 括号的类型没有匹配上。
- 第三种情况,字符串里右方向的括号多余了,所以不匹配。
class Solution {
public:
bool isValid(string s) {
if(s.size() % 2 != 0) return false;
stack<char> 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(']');
else if(st.empty() || st.top() != s[i]) return false;
else st.pop();
}
return st.empty();
}
};
1047. 删除字符串中的所有相邻重复项
https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/
栈记录 遍历数组当前元素时候,前一个元素是什么。
class Solution {
public:
string removeDuplicates(string s) {
string res;
for(auto t: s){
if(res.empty() || res.back() != t){
res.push_back(t);
}
else{
res.pop_back();
}
}
return res;
}
};
150. 逆波兰表达式求值
https://leetcode.cn/problems/evaluate-reverse-polish-notation/
逆波兰表达式:是一种后缀表达式,所谓后缀就是指运算符写在后面。
平常使用的算式则是一种中缀表达式,如 ( 1 + 2 ) * ( 3 + 4 ) 。
该算式的逆波兰表达式写法为 ( ( 1 2 + ) ( 3 4 + ) * ) 。
逆波兰表达式主要有以下两个优点:
- 去掉括号后表达式无歧义,上式即便写成 1 2 + 3 4 + * 也可以依据次序计算出正确结果。
- 适合用栈操作运算:遇到数字则入栈;遇到运算符则取出栈顶两个数字进行计算,并将结果压入栈中。
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<long long> st;
for(int i = 0; i < tokens.size(); i++){
if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/"){
long long n1 = st.top();
st.pop();
long long n2 = st.top();
st.pop();
if(tokens[i] == "+") st.push(n1 + n2);
else if(tokens[i] == "-") st.push(n2 - n1);
else if(tokens[i] == "*") st.push(n1 * n2);
else if(tokens[i] == "/") st.push(n2 / n1);
}
else{
st.push(stoll(tokens[i]));
}
}
return st.top();
}
};