leetcode 有效的括号https://leetcode.cn/problems/valid-parentheses/submissions/
class Solution {
public:
bool isValid(string s) {
stack<char> st;
vector<char> v;
for(int i=0;i<s.size();i++){
if(s[i]=='(' ||s[i]=='{'|| s[i]=='['){
st.push(s[i]);
}else{
if(!st.empty() &&st.top()=='(' && s[i]==')'){
st.pop();
}else if(!st.empty()&&st.top()=='[' && s[i]==']'){
st.pop();
}else if(!st.empty()&&st.top()=='{' && s[i]=='}'){
st.pop();
}else{
v.push_back(s[i]);
}
}
}
return st.empty() && v.empty();
}
};
解析: 栈模拟消消乐,加辅助vector数组。
class Solution {
public:
string removeDuplicates(string s) {
stack<int> st;
for(int i=0;i<s.size();i++){
if(!st.empty()&&s[i]==st.top()){
st.pop();
}else{
st.push(s[i]);
}
}
string ans="";
while(!st.empty()){
ans+=st.top();
st.pop();
}
reverse(ans.begin(),ans.end());
return ans;
}
};
解析:还是模拟消消乐哦
leetcode 逆波兰表达式https://leetcode.cn/problems/evaluate-reverse-polish-notation/submissions/
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
for(int i=0;i<tokens.size();i++)
{
if(tokens[i]=="+"||tokens[i]=="-"||tokens[i]=="*"||tokens[i]=="/")
{
int num1=st.top();
st.pop();
int num2=st.top();
st.pop();
if (tokens[i] == "+") st.push(num2 + num1);
if (tokens[i] == "-") st.push(num2 - num1);
if (tokens[i] == "*") st.push(num2 * num1);
if (tokens[i] == "/") st.push(num2 / num1);
}else
{
st.push(stoi(tokens[i]));
}
}
int result=st.top();
st.pop();
return result;
}
};
解析:遇到加减乘除就消消乐。