这道题与 “20.有效的括号” 思路相同
方法一:栈
时间复杂度:O(n)
空间复杂度:O(n)
class Solution
{
private:
stack<char> stk; //利用栈来解决
public:
string removeDuplicates(string s)
{
for (auto ch : s) //遍历string
{
if (stk.empty() == true) //如果栈空,那当然要入栈
{
stk.push(ch);
}
else //如果栈不空
{
if (stk.top() == ch) //那判断一下两个字符是否一样,一样的话就出栈
{
stk.pop();
}
else //不一样的话就进栈
{
stk.push(ch);
}
}
}
string temp; //我们将栈中元素导入一个string中
while (stk.empty() == false)
{
temp.push_back(stk.top());
stk.pop();
}
temp = string(temp.rbegin(), temp.rend()); //因为栈“后入先出”,所以要将temp中的元素逆序一下
return temp;
}
};
方法二:string模拟栈
时间复杂度:O(n)
空间复杂度:O(1)
class Solution
{
public:
string removeDuplicates(string s)
{
string temp;
for (auto ch : s)
{
if (temp.empty() == true)
{
temp.push_back(ch);
}
else
{
if (temp.back() == ch)
{
temp.pop_back();
}
else
{
temp.push_back(ch);
}
}
}
return temp;
}
};