算法刷题记录 Day10
Date: 2024.03.02
lc 150. 逆波兰表达式求值
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
for(auto& s: tokens){
if(s == "+" || s == "-" || s == "*" || s == "/"){
int num2 = st.top();
st.pop();
int num1 = st.top();
st.pop();
if(s == "+"){
st.push(num1 + num2);
}
else if(s == "-"){
st.push(num1 - num2);
}
else if(s == "*"){
st.push(num1 * num2);
}
else{
st.push(num1 / num2);
}
}
else{
st.push(stol(s));
}
}
return st.top();
}
};
lc 1047. 删除字符串中的所有相邻重复项
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
for(auto& a: s){
if(!st.empty() && st.top() == a)
st.pop();
else
st.push(a);
}
string res;
while(!st.empty()){
res += st.top();
st.pop();
}
reverse(res.begin(), res.end());
return res;
}
};
lc 20. 有效的括号
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(auto& a: s){
if(a == '(')
st.push(')');
else if (a == '{')
st.push('}');
else if(a == '[')
st.push(']');
else{
if(!st.empty() && a == st.top())
st.pop();
else{
return false;
}
}
}
if(st.empty()){
return true;
}
else{
return false;
}
}
};