gpt4 book ai didi

java - 字符串列表的组合

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:16:33 25 4
gpt4 key购买 nike

下面是我需要在特定条件下组合的字符串列表。

“MSD”、“EEE”、“RSR”、“OCL”、“SMS”、“RTS”

组合的条件是

  1. 组合应该至少有两个字符串(例如:(“EEE”
    ,"RSR") ,("EEE","RSR","OCL"))
  2. 组合应该由相邻的字符串组成(例如:("OCL","SMS"),("MSD","EEE","RSR")是有效的。但不是 ("EEE","OCL")。由于“EEE”和“OCL”彼此不相邻)

对于这个问题,Java 实现非常受欢迎。

public class Dummy {

public static void main(String[] args) {
String[] str = { "MSD" ,"EEE", "RSR", "OCL", "SMS","RTS" };
List<String> list = new ArrayList<>();
for (int j = 0; j < str.length; j++) {
String temp = "";
for (int i = j; i < str.length; i++) {
temp = temp + " " + str[i];
list.add(temp);
}
}

for (String string : list) {
System.out.println(string);
}
}
}

抱歉我试过的代码更新晚了

最佳答案

for (int j = 0; j < str.length; j++) {
String temp = "";
for (int i = j; i < str.length; i++) {
if ("".equals(temp))
temp = str[i]; // assign the String to temp, but do not add to list yet
else {
temp = temp + " " + str[i];
list.add(temp); // now that temp consists of at least two elements
// add them to the list
}
}
}

修复了单个条目也被列出的问题。从而导致:

MSD EEE
MSD EEE RSR
MSD EEE RSR OCL
MSD EEE RSR OCL SMS
MSD EEE RSR OCL SMS RTS
EEE RSR
EEE RSR OCL
EEE RSR OCL SMS
EEE RSR OCL SMS RTS
RSR OCL
RSR OCL SMS
RSR OCL SMS RTS
OCL SMS
OCL SMS RTS
SMS RTS

关于java - 字符串列表的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34530086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com