- 有效的括号
- 删除字符串中的所有相邻重复项
- 逆波兰表达式求值
20. 有效的括号
代码
class Solution {
public:
bool isValid(string s) {
stack<char> stk;
for (auto a: s){
if (a == '(') stk.push(')');
else if (a == '[') stk.push(']');
else if (a == '{') stk.push('}');
else if (stk.empty() || stk.top() != a) return false;
else stk.pop();
}
if (stk.size()) return false;
return true;
}
};
1047. 删除字符串中的所有相邻重复项
第一想法
- 栈中放入字母,如果发现和栈顶字母相同,栈顶就
pop()
,否则就加入,最后输出字符串 - 或者直接把返回的字符串作为栈,相同就去掉末尾,不相同就加入
代码
class Solution {
public:
string removeDuplicates(string s) {
stack<char> stk;
for (auto a: s){
if (stk.empty() || stk.top() != a) stk.push(a);
else stk.pop();
}
string res = "";
while (!stk.empty()){
res.push_back(stk.top());
stk.pop();
}
reverse(res.begin(), res.end());
return res;
}
};
150. 逆波兰表达式求值
第一想法
只要出现运算符,就要取stack
中的两位数字做运算,然后再放到其中
代码
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> stk;
for (auto a: tokens){
if (a == "+" || a == "-" || a == "*" || a == "/"){
int num1 = stk.top();
stk.pop();
int num2 = stk.top();
stk.pop();
if (a == "+") stk.push(num1 + num2);
else if (a == "-") stk.push(num2 - num1);
else if (a == "*") stk.push(num1 * num2);
else if (a == "/") stk.push(num2 / num1);
}else{
stk.push(stoi(a));
}
}
return stk.top();
}
};