我试着用+操作符在字符串末尾追加字符,解决了一个编码问题,但给出的解决方案是超过内存限制。然后我看到使用+=来追加字符的解决方案。这两种方法在时间复杂度和内存复杂度上有什么区别吗?
例子 - 我的解决方案
string arrangeWords(string text) {
text[0] = text[0] + 32;
text = text + ' ';
string temp = "";
map < int, vector < string >> mp;
for (char c: text) {
if (c != ' ')
temp = temp + c; //---Notice this line
else {
mp[temp.size()].push_back(temp);
temp = "";
}
}
string res = "";
for (auto it: mp)
for (auto j: it.second)
res = res + j + ' '; //----Notice this line
res[0] = toupper(res[0]);
return res.substr(0, res.size() - 1);
}
已接受的解决方案 -
string arrangeWords(string text) {
text[0] += 32;
text += ' ';
string temp = "";
map < int, vector < string >> mp;
for (char c: text) {
if (c != ' ')
temp += c; //Notice this line change
else {
mp[temp.size()].push_back(temp);
temp = "";
}
}
string res = "";
for (auto it: mp)
for (auto j: it.second)
res += j + ' '; //Notice this line change
res[0] = toupper(res[0]);
return res.substr(0, res.size() - 1);
}
temp = temp + c;
创建一个临时 temp + c
(这可能需要(缓慢)分配),然后再分配给 temp
. (复杂度为O(n))
temp += c;
重用缓冲区,如果足够大的话(复杂度为O(1)),否则应该进行重新分配(然后,它将 "类似于 "上述方法)(复杂度为O(n))。(摊销的复杂度为 O(1)
)
此外,发生分配的情况较少,出现碎片化内存的机会较少。