使用栈来完成这道题目,遍历字符串每个字符,如果栈为空,或者字符与栈顶字符不同,则插入字符;如果字符与栈顶字符相同,则说明出现重复项,从栈中删除栈顶元素。遍历完成后栈中的元素便是删除所有相邻重复项后的字符串,只不过出栈后所有元素的顺序时相反的。
- 首次完成时,使用一个新的栈来接收这些元素,然后从新的栈重新出栈,这样字符串的顺序便会改变,成为顺序的
- 改进方法是先出栈,然后对字符串进行反转
- 还可以直接拿返回的字符串作栈,省去了创建栈和栈转为字符串的操作。
class Solution {
public:
string removeDuplicates(string s) {
stack<char> stIn;
stack<char> stOut;
for(auto ch : s){
if(stIn.empty() || stIn.top() != ch){
stIn.push(ch);
}else{
stIn.pop();
}
}
while(!stIn.empty()){
stOut.push(stIn.top());
stIn.pop();
}
string result = "";
while(!stOut.empty()){
result += stOut.top();
stOut.pop();
}
return result;
}
};
改进后:
class Solution {
public:
string removeDuplicates(string S) {
stack<char> st;
for (char s : S) {
if (st.empty() || s != st.top()) {
st.push(s);
} else {
st.pop(); // s 与 st.top()相等的情况
}
}
string result = "";
while (!st.empty()) { // 将栈中元素放到result字符串汇总
result += st.top();
st.pop();
}
reverse (result.begin(), result.end()); // 此时字符串需要反转一下
return result;
}
};
返回字符串作为栈:
class Solution {
public:
string removeDuplicates(string S) {
string result;
for(char s : S) {
if(result.empty() || result.back() != s) {
result.push_back(s);
}
else {
result.pop_back();
}
}
return result;
}
};