1.删除字符串中的所有相邻项
link:1047. 删除字符串中的所有相邻重复项 - 力扣(LeetCode)
思路:
栈+模拟
code
class Solution {
public:
string removeDuplicates(string s) {
// 栈来模拟即可
// string代替栈
string ans;
for(int i = 0; i < s.size(); i++)
{
if((!ans.empty()) && ans.back() == s[i]) ans.pop_back();
else ans.push_back(s[i]);
}
return ans;
}
};
2.比较含退格的字符串
link:844. 比较含退格的字符串 - 力扣(LeetCode)
思路
栈 + 模拟
code
class Solution {
public:
bool backspaceCompare(string s, string t) {
return f(s) == f(t);
}
string f(string& s)
{
string ans;
for(int i = 0; i < s.size(); i++)
{
if(s[i] != '#') ans.push_back(s[i]);
else if(!ans.empty()) ans.pop_back();
}
return ans;
}
};
3.基本计算器II
link:227. 基本计算器 II - 力扣(LeetCode)
思路:
code
class Solution {
public:
int calculate(string s) {
string ops("+-*/");
vector<int> st;
char op = '+';
for(int i = 0; i < s.size(); )
{
int left = i, right = i + 1;
while(right < s.size() && ops.find(s[right]) == string::npos) right++;
printf("left = %d, right = %d\n", left, right);
// [left, right - 1]都是num; right 为ops
int num = stoi(string(s.begin() + left, s.begin() + right));
if (op == '+') st.push_back(num);
else if(op == '-') st.push_back(-num);
else if(op == '/')
{
int pop = st.back();
st.pop_back();
st.push_back(pop / num);
}
else if(op == '*')
{
int pop = st.back();
st.pop_back();
st.push_back(pop * num);
}
op = s[right];
i = right + 1;
}
int ans = 0;
for(const auto& e:st)
{
ans += e;
}
return ans;
}
};
4.字符码解码
link:
思路
栈 + 模拟
code
class Solution {
public:
string decodeString(string s) {
string ans;
// for(int i = 0; i < s.size(); i++)
for(const auto& e:s)
{
if(e != ']') ans.push_back(e);
else
{
string str;
// 获取重复字符串
for(char ch = ans.back(); ch != '['; ans.pop_back(), ch = ans.back())
str = ch + str;
ans.pop_back();
// 获取数字
string snum = "";
for(char ch = ans.back(); ch >= '0' && ch <= '9'; )
{
snum = ch + snum;
ans.pop_back();
if(ans.empty()) break;
ch = ans.back();
}
int mult = stoi(snum);
for(int i = 0; i < mult; i++) ans += str;
}
}
return ans;
}
};
5.验证栈序列
link:946. 验证栈序列 - 力扣(LeetCode)
思路
栈 + 模拟
code
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
stack<int> st;
int idx = 0;
for(const auto& e:pushed)
{
st.push(e);
while((!st.empty()) && st.top() == popped[idx])
{
st.pop();
idx++;
}
}
return st.empty();
}
};