【问题标题】:How to concatenate a string with all other strings in the list in O(n)如何在 O(n) 中将字符串与列表中的所有其他字符串连接起来
【发布时间】:2018-01-26 13:21:07
【问题描述】:

我想将一个字符串与列表中的所有其他字符串连接起来,我正在使用嵌套 for 循环,但该方法对于大型列表效率不高。 谁能帮我在 o(n) 或 o(nlogn) 中做到这一点? 这是我的代码。

List<String> allConcatenatedStrings=new List<String>();
for(int i=0;i<listOfStrings.length-1;i++){                               
   for(int j=i+1;j<listOfStrings.length;j++){
      String temp= String.join("",listOfStrings[i],listOfStrings[j]);
      allConcatenatedStrings.add(temp);
   }
}

【问题讨论】:

  • tickets 是什么意思listOfStrings
  • 什么是输入,什么是预期输出?
  • 我仍然没有真正得到你想要实现的目标。您想将哪个字符串与哪个字符串连接?
  • 如果您需要所有这些temp 字符串,那么您编写的代码将尽可能高效。尽管我假设您的代码有效(并且它与您在此处发布的内容足够相似) - 如果不是这种情况,您还应该发布您的输入、预期输出和实际输出(无论如何这通常是一个好主意)。如果你想用它来解决其他问题,你应该发布一个描述以及minimal reproducible example。相关:What is the XY problem?
  • 你对所有的字符串做了什么?您的示例代码将它们保存到一个临时变量中,该变量会立即丢失。

标签: java string for-loop concatenation


【解决方案1】:

看看StringBuilder,这是一种连接字符串的有效方法:

StringBuilder sb = new StringBuilder();
//Inside for loop:
sb.append(stringToAppend);

//after for loop:
String result = sb.toString();

【讨论】:

  • 嗨 Johan,我想一次只连接 2 个字符串,然后计算一个逻辑。我只想要一种有效的方法来迭代和附加字符串。谢谢
【解决方案2】:

您可以为此使用 Java 8 Stream API:

List<String> listOfStrings = Arrays.asList("Hello ","World",","," apprentice");
String concatenatedString = String.join("", listOfStrings); 

System.out.println(concatenatedString); // Hello World, apprentice

【讨论】:

  • 嗨 Georg,我想一次只连接 2 个字符串,然后计算一个逻辑。我只想要一种有效的方法来迭代和附加字符串。谢谢
  • 这没有出现在您的解释中。然后请在您的问题中添加评论,在连接字符串之前应该如何处理。
猜你喜欢
  • 2020-12-11
  • 1970-01-01
  • 1970-01-01
  • 2020-07-31
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多