1.删除字符串中的所有相邻重复项
删除字符串中的所有相邻重复项
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/9263d34632bb4e2f97b020f667ef4c70.png)
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.比较含退格的字符串
比较含退格的字符串
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/b7ffed5c41224f8daa9541e4c79991a5.png)
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
基本计算器II
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/6ef7117f76ec4093a5b2e34a5d4c8235.png)
class Solution {
public:
int calculate(string s) {
vector<int> st;
char op = '+';
int i = 0,n = s.size();
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');
if(op == '+') st.push_back(tmp);
else if(op == '-') st.push_back(-tmp);
else if(op == '*') st.back()*=tmp;
else if(op == '/') st.back() /= tmp;
}
else
{
op = s[i];
i++;
}
}
int ret = 0;
for(auto x:st) ret+=x;
return ret;
}
};
4.字符串解码
字符串解码
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/d423eff78a764744840dc5f1b3826890.png)
class Solution {
public:
string decodeString(string s) {
stack<string> st;
stack<int> nums;
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');
nums.push(tmp);
}
else if(s[i] == '[')
{
i++;
string tmp;
while(s[i]>='a'&&s[i]<='z') tmp+=s[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++];
st.top()+=tmp;
}
}
return st.top();
}
};
5.验证栈序列
验证栈序列
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/373d603a04224c298be71e5783f57b8c.png)
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
stack<int> st;
int i =0,n = popped.size();
for(auto ch:pushed)
{
st.push(ch);
while(st.size() && st.top() == popped[i])
{
st.pop();
i++;
}
}
return i==n;
}
};