【问题标题】:Is there difference in string concatenation using shortand operator?使用 shortand 运算符进行字符串连接有区别吗?
【发布时间】: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]);(更具可读性和便携性)。

标签: c++ string shorthand


【解决方案1】:

temp = temp + c; 在分配给temp 之前创建一个临时的temp + c(这可能需要(缓慢)分配)。 (复杂度为 O(n))

temp += c; 重用缓冲区如果足够大(复杂度 O(1)),否则应该进行重新分配(然后,它将与上述方法“相似”)(复杂度 O(n))。 (摊销复杂度为O(1)

此外,分配更少,内存碎片的机会也更少。

【讨论】:

  • 字符串的正常缓冲区大小是多少?是否取决于使用的语言?
  • @Ash • 编译器实现细节。您可以在给定的字符串上使用 s.capacity() 进行检查。如果您提前知道需要多少空间,比如 10,000,您可以s.reserve(10000)
猜你喜欢
  • 1970-01-01
  • 2012-01-20
  • 2012-05-07
  • 2023-03-13
  • 1970-01-01
  • 2013-09-21
  • 2018-11-10
相关资源
最近更新 更多