20. 有效的括号
class Solution {
public:
bool isValid(string s) {
if(s.size()<2) return false;
stack<char>stk;
for(char c:s){
if(c=='(') stk.push(')'); //左
else if(c=='[') stk.push(']'); //左
else if(c=='{') stk.push('}'); //左
else if(!stk.empty()&&c==stk.top()){//右,且匹配
stk.pop();
}
else return false;
}
return stk.empty();
}
};
1047. 删除字符串中的所有相邻重复项
栈
class Solution {
public:
string removeDuplicates(string s) {
stack<char>stk;
for(char c:s){
if(!stk.empty()&& c==stk.top()){
stk.pop();
}else{
stk.push(c);
}
}
string ans="";
while(!stk.empty()){
ans+=stk.top();
stk.pop();
}
reverse(ans.begin(),ans.end());
return ans;
}
};
直接用一个字符串当栈
class Solution {
public:
string removeDuplicates(string s) {
string ans="";
for(char c:s){
if(!ans.empty()&&ans.back()==c){
ans.pop_back();
}else{
ans.push_back(c);
}
}
return ans;
}
};
150. 逆波兰表达式求值
注意入栈顺序(计算顺序)和出栈顺序是反过来的
class Solution {
public:
int evalRPN(vector<string>& tokens) {
long long num1, num2;
stack<long long> stk;
for (string s : tokens) {
if (s == "+" || s == "-" || s == "*"||s == "/") {
num1 = stk.top();
stk.pop();
num2 = stk.top();
stk.pop();
if (s == "+")
stk.push(num2 + num1);
else if (s == "-")
stk.push(num2 - num1);
else if (s == "*")
stk.push(num2 * num1);
else if (s == "/")
stk.push(num2 / num1);
}
else stk.push(stoll(s));
}
return stk.top();
}
};