栈
目录
试题1:删除字符串中的所有相邻重复项

算法原理
解法:模拟栈

代码编写
cpp
class Solution
{
public:
string removeDuplicates(string s)
{
string ret;
for(auto ch : s)
{
if(ret.size() && ch == ret.back())
{
ret.pop_back();
}
else
{
ret += ch;
}
}
return ret;
}
};
试题2:比较含退格的字符串

算法原理
解法:模拟栈

代码编写
cpp
class Solution
{
public:
bool backspaceCompare(string s, string t)
{
return changeStr(s) == changeStr(t);
}
string changeStr(string &s)
{
string ret;
for(auto ch : s)
{
if(ch != '#')
{
ret += ch;
}
else
{
if(ret.size())
{
ret.pop_back();
}
}
}
return ret;
}
};
试题3:基本计算器II

算法原理
解法:模拟栈
遇到操作符:更新操作符栈
遇到数字:提取数字,分情况讨论
根据操作符栈的符号
- 加号:数字入数字栈
- 减号:数字的相反数入栈
- 乘号:直接与数字栈栈顶元素相乘
- 除号:直接与数字栈栈顶元素相除

代码编写
cpp
class Solution
{
public:
int calculate(string s)
{
// 用数组模拟栈结构
vector<int> st;
int i = 0, n = s.size();
char op = '+';
while(i < n)
{
if(s[i] == ' ')
{
i++;
}
else if(s[i] >= '0' && s[i] <= '9')
{
int tmp = 0;
while(i < n && s[i] >= '0' && s[i] <= '9')
{
tmp = tmp * 10 + (s[i] - '0');
i++;
}
if(op == '+')
{
st.push_back(tmp);
}
else if(op == '-')
{
st.push_back(-tmp);
}
else if(op == '*')
{
st.back() *= tmp;
}
else
{
st.back() /= tmp;
}
}
else
{
op = s[i];
i++;
}
}
int ret = 0;
for(auto x : st)
{
ret += x;
}
return ret;
}
};
试题4:字符串解码

算法原理
解法:模拟栈
遇到数字:提取数字,放入数字栈
遇到左括号:提取后面的字符串,放入字符串栈
遇到右括号:拿出两个栈的栈顶元素解析,放到字符串栈的栈顶元素后面
遇到单独字符:提取字符串,放到字符串栈的栈顶元素后面

代码编写
cpp
class Solution
{
public:
string decodeString(string s)
{
stack<int> nums;
stack<string> st;
st.push("");
int i = 0, n = s.size();
while(i < n)
{
if(s[i] >= '0' && s[i] <= '9')
{
int tmp = 0;
while(s[i] >= '0' && s[i] <= '9')
{
tmp = tmp * 10 + (s[i] - '0');
i++;
}
nums.push(tmp);
}
else if(s[i] == '[')
{
i++;// 跳过左括号
string tmp;
while(s[i] >= 'a' && s[i] <='z')
{
tmp += s[i];
i++;
}
st.push(tmp);
}
else if(s[i] == ']')
{
string tmp = st.top();
st.pop();
int k = nums.top();
nums.pop();
while(k--)
{
st.top() += tmp;
}
i++;// 跳过右括号
}
else
{
string tmp;
while(i < n && s[i] >= 'a' && s[i] <='z')
{
tmp += s[i];
i++;
}
st.top() += tmp;
}
}
return st.top();
}
};
试题5:验证栈序列

算法原理
解法:模拟栈
让元素一直进栈
进栈的同时判断是否出栈,所有元素进栈完后
判断i是否遍历完毕,或者判断栈是否为空

代码编写
cpp
class Solution
{
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped)
{
stack<int> st;
int i = 0, n = popped.size();
for(auto x : pushed)
{
st.push(x);
while(st.size() && st.top() == popped[i])
{
st.pop();
i++;
}
}
return i == n;
}
};