如何在一个句子JAVA中连接所有单词表示的案例

时间:2016-03-27 22:48:19

标签: java string concatenation permutation

输入 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"

有人能解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

这样的事情怎么样?

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

我相信代码的问题是,只有在递归到达结束时才将元素添加到列表中,而不允许使用您想要的子元素。