删除字符串中的所有相邻重复项
实现方法
使用栈来实现记录前置字母(包括删除前和删除后,所以需要动态增删的容器);
基础思想很简单,代码如下:
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
int len = s.size();
for(int i = 0; i < len; i++){
if(st.empty()||st.top()!=s[i])st.push(s[i]);
else if(st.top() == s[i])st.pop();
}
stack<char> rst;
while(!st.empty()){
char x = st.top();
st.pop();
rst.push(x);
}
string ss;
while(!rst.empty()){
char x = rst.top();
rst.pop();
ss += x;
}
return ss;
}
};

浙公网安备 33010602011771号