题目描述
思路
首先阅读题干,发现可以用栈来实现。
具体实现思路:
从左到右依次遍历字符串,如果栈为空 或者 该元素和栈顶元素不相等 ,就push进栈。
否则,pop()掉最上面的元素。
重复以上过程,直至遍历完整个字符串。
完整代码
class Solution {
public:
string removeDuplicates(string s)
{
string res="";
stack<char> st;
for(int i=0;i<s.size();i++)
{
if(st.empty()||st.top()!=s[i])
{
st.push(s[i]);
}
else
{
st.pop();
}
}
while(!st.empty())
{
res+=st.top();
st.pop();
}
reverse(res.begin(),res.end());
return res;
}
};