算法———栈
目录
一、算法解析
二、题目
删除字符串中所有相邻重复项
(1)题目
(2)解题思路
(3)代码实现
比较含退格的字符串
(1)题目
(2)解题思路
(3)代码实现
基本计算机II
(1)题目
(2)解题思路
(3)代码实现
字符串解码
(1)题目
(2)解题思路
(3)代码实现
编辑
验证栈序列
(1)题目
(2)解题思路
(3)代码书写
一、算法解析
在一些题目中我们可以使用栈来化简题目
二、题目
删除字符串中所有相邻重复项
https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/
(1)题目

(2)解题思路
我们可以用字符串模拟一个栈,如果下一个元素和栈顶元素相同,就pop,反之push

(3)代码实现

class Solution
{
public:string removeDuplicates(string s) {string s1;for(auto e : s){if(s1.size()&&e == s1.back()) s1.pop_back();else s1.push_back(e);}return s1;}
};
比较含退格的字符串
https://leetcode.cn/problems/backspace-string-compare/
(1)题目

(2)解题思路
这道题跟上一道题十分相似,我们可以使用一个字符串s1模拟栈,首先选择一个字符串s 遍历他,如果s1不是空串,且当前遍历s的字母是#就pop,其余的情况push当前遍历的s字母,t字符串重复上述操作,使用一个字符串s2,最后判断二者是否相同
(3)代码实现

class Solution{
public:bool backspaceCompare(string s, string t){string s1;string s2;for(auto e : s){if(e!='#')s1.push_back(e);else{if(s1.size()) s1.pop_back();}}for(auto e : t){if(e!='#')s2.push_back(e);else{if(s2.size()) s2.pop_back();}}return s1 == s2;}
};
基本计算机II
https://leetcode.cn/problems/basic-calculator-ii/
(1)题目

(2)解题思路
我们可以使用双栈来模拟计算机的过程

(3)代码实现
class Solution
{
public:int calculate(string s) {vector<int> st;int i = 0;int 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;}
};
字符串解码
https://leetcode.cn/problems/decode-string/
(1)题目

(2)解题思路
遍历字符串,建立两个栈

如果遇到数字提取提取数字入栈,如果遇到“【” 把后面的字符串提取出来,放入“字符串栈中”;
遇到‘】’ 解析,然后放到“字符串”栈顶的字符串后面,遇到单独的字符提取出来这个字符串,直接放在“字符串”
(3)代码实现
class Solution
{
public:string decodeString(string s) {stack<int> nums;stack<string> st;st.push("");int n = s.size();int i = 0;while(i<n){if(s[i] >= '0'&& s[i] <= '9'){int tmp = 0;while(s[i] >= '0' && s[i] <= '9'){int x = s[i] - '0';tmp = tmp * 10 + x;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] == ']'){int k = nums.top();nums.pop();string s1 = st.top();st.pop();while(k--){st.top() += s1;}i++;}else{string tmp = "";while(i < n && s[i] >= 'a' && s[i] <= 'z'){tmp+=s[i];i++;}st.top() += tmp;}}return st.top();}
};
验证栈序列
https://leetcode.cn/problems/validate-stack-sequences/
(1)题目

(2)解题思路
我们可以模拟栈的过程,一直不停的入栈知道和pop相同在出栈,然后重复上述操 作
(3)代码书写

class Solution
{
public:bool validateStackSequences(vector<int>& pushed, vector<int>& popped){stack<int> s;int j = 0;for(int i = 0; i<pushed.size(); i++){s.push(pushed[i]);while(!s.empty()&&s.top()==popped[j]){s.pop();j++;}}return s.empty();}
};

