【发布时间】:2020-09-05 12:12:37
【问题描述】:
我尝试使用 + 运算符将字符附加到字符串的末尾以解决编码问题。该解决方案超出了内存限制。然后我看到了使用 += 附加字符的解决方案。在时间复杂度或内存复杂度的情况下,两者有什么区别吗?
示例 - 我的解决方案
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);
}
【问题讨论】:
-
避免使用神奇的数字:
text[0] = text[0] + 32;应该是text[0] = tolower(text[0]);(更具可读性和便携性)。