gpt4 book ai didi

java - 如何连接句子中单词呈现的所有情况JAVA

转载 作者:行者123 更新时间:2023-12-01 10:09:12 25 4
gpt4 key购买 nike

输入: n 个单词列表“word1 word2 word3...wordn

输出:所有排列情况串联的字符串列表表示为:

s1: "word1 word2"
s2: "word1 word3"
s3: "word2 word1"
s4: "word2 word3"
s5: "word3 word1"
s6: "word3 word1"
s7: "word1 word2 word3"
s8: "word1 word3 word2"
s9: "word2 word1 word3"
s10: "word2 word3 word1"
s11: "word3 word1 word2"
s12: "word3 word2 word1"
...
sm: "wordn...word3 word 2 word 1"

我尝试这段代码:

    public static List<String> PermuteWords(String s){
String[] ss = s.split(" ");
boolean[] used = new boolean[ss.length];
String res = "";
List<String> list = new ArrayList<String>();
permute(ss, used, res, 0, list);
return list;
}

private static void permute(String[] ss, boolean[] used,
String res, int level, List<String> list) {

if (level == ss.length && res != ""){
list.add(res);
return;
}

for (int i = 0; i < ss.length; i++) {
if (used[i]) {
continue;
}
used[i] = true;
permute(ss, used, res + " " + ss[i], level + 1, list);
used[i] = false;
}
}

public static void main(String args[]){

String inputString="word1 word2 word3";
List<String> test=PermuteWords(inputString);

for (int i = 0; i < test.size(); i++) {
System.out.println(test.get(i));
}
}

输出:

 word1 word2 word3
word1 word3 word2
word2 word1 word3
word2 word3 word1
word3 word1 word2
word3 word2 word1

但是它缺少一些案例:

s1: "word1 word2"
s2: "word1 word3"
s3: "word2 word1"
s4: "word2 word3"
s5: "word3 word1"
s6: "word3 word1"

谁能解决这个问题吗?

最佳答案

像这样怎么样?

private static void permute(String[] ss, boolean[] used,
String res, int level, List<String> list) {

// End case
if (level == ss.length && res != ""){
list.add(res);
return;
}

for (int i = 0; i < ss.length; i++) {
// Check if the string is currently used
if (used[i]) {
continue;
}
// Check if res is empty or a single word
if(level > 1)
list.add(res);
used[i] = true;
permute(ss, used, res + " " + ss[i], level + 1, list);
used[i] = false;
}
}

输出:

 word1 word2
word1 word2 word3
word1 word3
word1 word3 word2
word2 word1
word2 word1 word3
word2 word3
word2 word3 word1
word3 word1
word3 word1 word2
word3 word2
word3 word2 word1

我认为代码的问题在于,仅当递归到达末尾时,元素才会添加到列表中,而不允许像您想要的那样的子元素。

关于java - 如何连接句子中单词呈现的所有情况JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36253605/

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