1.使用栈
借用栈,类似括号匹配。当前元素等于栈顶元素,则栈顶元素出栈;否则,当前元素入栈,最终,栈中保存的即是结果
代码如下:
class Solution {
public:
string removeDuplicates(string S) {
stack<char> s;
int i=0;
while(i<S.size())
{
if(s.empty()||S[i]!=s.top())
s.push(S[i]);
else
s.pop();
i++;
}
string ans;
while(!s.empty())
{
ans+=s.top();
s.pop();
}
reverse(ans.begin(),ans.end());
return ans;
}
};
2.原地算法
使用原数组存放当前有效的元素
代码如下:
class Solution {
public:
string removeDuplicates(string S) {
int top = 0;//top表示当前有效的元素个数
for (int i=0;i<S.size();i++) {
if (top == 0 || S[top - 1] != S[i]) {
S[top++] = S[i];
} else {
top--;
}
}
S.resize(top);
return S;
}
};