【问题标题】:String concatenation time complexity S+=X and S = S+X字符串连接时间复杂度 S+=X 和 S = S+X
【发布时间】:2021-11-27 21:21:43
【问题描述】:

我正在解决 leetcode 上的一个免费问题,当我使用 st = st+b 而不是 st+=b 时,我得到了 TLE(超出时间限制)。我虽然两个操作是一样的。他们不是吗。请详细说明。如果还有其他问题,请在答案中提及。

st 最初是一个空字符串,b 是一个字符

图片链接更清晰:

Here you can see I used st+=b

Here I used st=st+b

string frequencySort(string s) {
    priority_queue<pair<int,char>> pq;
    unordered_map<char,int> m;
        for(int i = 0;i<s.size();i++)
            m[s[i]]++;
    for(auto x:m)
        pq.push(make_pair(x.second,x.first));
    string st = "";
    while(!pq.empty()){
        int x = pq.top().first;
        char b = pq.top().second;
        while(x--)
        st=st+b;
        
        pq.pop();
    }
    return st;
}

【问题讨论】:

  • There is a difference between += and + for c++ string concatentation。 += 运算符利用真正的连接,将具有更好的性能。 A = A+B 方法会复制并且更昂贵。
  • 这能回答你的问题吗? Efficient string concatenation in C++
  • 它们不一样,但是这段代码运行在什么样的数据上呢?通常你不会看到差异,除非有 lot 的字符串操作正在进行。除非超时错误的原因是数据量很大,或者while 循环执行了数千(可能是数百万)次,否则+= 可能非常接近超时,您仍然需要使用不同的方法。
  • 此外,这些在线竞赛编码网站有一些问题(如果你用 C++ 解决它们),如果使用的基本算法或方案很慢,那么很少做这样的改变会产生很大的影响。我敢打赌+= 接近时间限制,但只是错过了它,而使用+ 会让你超过阈值。此外,这些网站并不热衷于各种语言的特定怪癖,例如 +=+ 的微妙之处。如果使用的方法是他们心目中的最佳方法,他们的问题通常会超过时间限制。

标签: c++ string time-complexity concatenation


【解决方案1】:

它们不一样。 operator+= 不需要创建新对象。在最好的情况下,字符串有足够的容量并且不必重新分配。另一方面,operator+ 返回一个新的string。为了说明,请考虑 operator+operator+= 的某种典型实现:

#include <string>
#include <iostream>
    
struct my_string {
    std::string value;

    my_string& operator+=(const my_string& other) {
        value += other.value;
        return *this;
    }

    my_string operator+(const my_string& other) {
        my_string result{*this};
        return result+=other;
    }
};

int main() {
    my_string f{"foo"};
    my_string b{"bar"};
    std::cout << (f+b).value << "\n";
    std::cout << (f+=b).value;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 2023-03-20
    • 2019-12-17
    • 2016-11-24
    相关资源
    最近更新 更多