1047. 删除字符串中的所有相邻重复项

这道题与 “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;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值