1047. 删除字符串中的所有相邻重复项 - 力扣(LeetCode)
class Solution {
public:
string removeDuplicates(string s) {
string stack;
for(char& ch:s){
if(stack.size()>0&&ch==stack.back()){
stack.pop_back();
}else{
stack.push_back(ch);
}
}
return stack;
}
};
844. 比较含退格的字符串 - 力扣(LeetCode)
class Solution {
public:
bool backspaceCompare(string s, string t) {
string tmp_s;
string tmp_t;
for(char& ch:s){
if(ch=='#'){
if(tmp_s.size()>0)
tmp_s.pop_back();
}else{
tmp_s.push_back(ch);
}
}
for(char& ch:t){
if(ch=='#'){
if(tmp_t.size()>0)
tmp_t.pop_back();
}else{
tmp_t.push_back(ch);
}
}
if(tmp_s==tmp_t)
return true;
return false;
}
};
227. 基本计算器 II - 力扣(LeetCode)
class Solution {
public:
int calculate(string s) {
vector<int> stack;//栈内不存在加减乘除符号,符号遍历时用op保存,如果有括号的话,需要另一个栈,然后加减符号可以用正负代替插入。
int i=0; int n=s.size();
char op='+';
while(i<n){
if(s[i]==' ') i++;
else if(0+'0'<=s[i]&&s[i]<=0+'9'){
//提取数字
int tmp=s[i++]-'0';
while(0+'0'<=s[i]&&s[i]<=0+'9') tmp+=tmp*10+s[i++]-'0';
cout<<"op: "<<op<<endl;
cout<<tmp<<endl;
if(op=='+') stack.push_back(tmp);
else if(op=='-') stack.push_back(-tmp);
else if(op=='*'){
int tmp1=stack.back();//必须在push前先pop
stack.pop_back();
stack.push_back(tmp1*tmp);
// stack.pop_back();
}else if(op=='/'){
int tmp1=stack.back();
stack.pop_back();
stack.push_back(tmp1/tmp);
}
for(int num:stack){cout<<num<<" ";}cout<<endl;
}else {
// cout<<"op: "<<op<<endl;
op=s[i++];
}
}
int ret=0;
for(int& num:stack){
// cout<<num<<endl;
ret+=num;
}
return ret;
}
};
946. 验证栈序列 - 力扣(LeetCode)
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped){
stack<int> st;
int i=0; int n=popped.size();
for(int &val : pushed){
st.push(val);
while(st.size()&&st.top()==popped[i]){
st.pop();
i++;
}
}
return st.size()==0;
}
};