c++中string拼接效率

本文探讨了C++中string对象拼接时使用+和+=操作符的区别。+操作符会导致创建新对象,而+=操作符则直接在原对象上进行追加,效率更高。在解决LeetCode 1047题时,使用+=进行尾插法避免了头插法导致的时间超限问题,使得代码能够顺利通过测试。
摘要由CSDN通过智能技术生成

c++中string拼接效率

+和 +=的差别: + 相比于 += 执行过程中会多产生一个新对象。

str = str + a;

该语句先将等号右边的两个string对象内容相加,得到一个新的string对象。再把这个新的对象赋给等号左边的string对象。

str += a;

该语句直接将等号右边的string对象内容追加到左边的string对象后面。

leetcode1047:删除字符串中的所有相邻重复项

class Solution {
public:
    string removeDuplicates(string s) {
        stack<char> _stack;
        string result;
        for(int i = 0;i < s.size();i++)
        {
            if(!_stack.empty() && s[i] == _stack.top())
            {
                _stack.pop();
            }else{
                _stack.push(s[i]);
            }     
        }
        while(!_stack.empty())
        {
            result = _stack.top() + result;//头插法(超时的罪魁祸首)
            _stack.pop();
        }
        return result;
    }
};

使用赋值语句使结果超时,无法通过。

class Solution {
public:
    string removeDuplicates(string s) {
        stack<char> _stack;
        string result;
        for(int i = 0;i < s.size();i++)
        {
            if(!_stack.empty() && s[i] == _stack.top())
            {
                _stack.pop();
            }else{
                _stack.push(s[i]);
            }     
        }
        while(!_stack.empty())
        {
            result += _stack.top();//尾插
            _stack.pop();
        }
        reverse (result.begin(), result.end()); // 字符串反转
        return result;
    }
};

成功通过

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值