2021-07-07

题目

class Solution {
public:
/*
    当栈为空时:
        1. 字符串不为空,进栈;
        2. 字符串为空,返回
    当栈不为空时:
        比较栈顶和字符
            a)相等,则出栈
            b)不等,则入栈
    当字符串遍历完成,将栈里的字符都插入到res的 0 位置,耗时了。
    先添加到尾部,再翻转。
*/  
    string removeDuplicates(string s) {
        stack<char> st1;
        string res;
        for (int i = 0; i < s.length(); i++) {
            if (st1.empty()) {
                st1.push(s[i]);
            }
            else {
                if (st1.top() == s[i]) {
                    st1.pop();
                }
                else {
                    st1.push(s[i]);
                }
            }
        }
        while (!st1.empty()) {
            char x = st1.top();
            //Char 17: error: no matching member function for call to 'insert'          
            // res.insert(0, x);

            // 每次在字符串的首部添加字符。。导致程序消耗增加。
            // res = x + res;

            // 先添加完,后翻转
            res += x;
            st1.pop();
        }
        // 用algorithm函数
        //reverse(res.begin(), res.end());

        // 1 2 3 4 5
        // 原地翻转
        int len = res.length();
        for (int i = 0; i < len/2; i++) {
            swap(res[i], res[len - i - 1]);
        }

        return res;
    }
};

在这里插入图片描述

总结

  • 想问题的时候,没注意内存消耗问题
  • strrev函数只对字符数组有效,对string类型是无效的。
  • reverse函数是反转容器中的内容,对字符数组无效。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值