【问题标题】:Generate word combinations from a list of strings in java从java中的字符串列表生成单词组合
【发布时间】:2020-08-05 00:50:46
【问题描述】:

我想在 java 中创建一个算法,我可以在其中传递一个字符串列表,它会返回一个新列表,其中包含列表中所有可能的字符串组合。

例子:

String[] listWords = new String[] {

                "windows",
                "linux",
                "mac",
                "10",
                "20"

        };

我想通过传递返回所有可能组合的列表来调用方法。

combinations(listWords);

这是我想要的结果:

windows,linux,mac,10,20,windowslinux,linuxwindows,windowsmac,windows10,10windows,windows20,20windows,windowslinuxmac1020,windowsmaclinux20,mac10,mac20,20mac,20mac10,windowsmac,macwindows...

我试过了:

public String[][] combinations (String[] ports) {
        List<String[]> combinationList = new ArrayList<String[]>();
        for ( long i = 1; i < Math.pow(2, ports.length); i++ ) {
            List<String> portList = new ArrayList<String>();
            for ( int j = 0; j < ports.length; j++ ) {
                if ( (i & (long) Math.pow(2, j)) > 0 ) {
                    portList.add(ports[j]);
                }
            }
            combinationList.add(portList.toArray(new String[0]));
        }
        return combinationList.toArray(new String[0][0]);
    }

但这会返回:

这不是我想要的。结果必须是:

列表:[windows, linux, windowslinux, linuxwindows, windows10, 10windowsmaclinux...]

在java中可以做到这一点吗?谢谢谁能帮忙:)

【问题讨论】:

  • 顺便给个提示:List.of( "windows", "linux", "mac", "10", "20" )

标签: java arrays string combinations


【解决方案1】:

如果我的理解正确,以下将解决问题。

您可以从您拥有的单词列表开始迭代地构建结果,并在每次迭代中添加越来越长的单词。第一次迭代为您提供原始列表。第二次迭代为每个单词添加一个新单词,为您提供 2 个单词的排列。第三次迭代为每个单词添加一个新单词,为您提供 3 个单词的排列,依此类推。

List<String> getWordPermutations(List<String> words) {

    List<String> result = new ArrayList<>(words);
    List<String> oldPermutations = new ArrayList<>(words);

    for (int i = 1; i < words.size(); i++) {
        List<String> newPermutations = new ArrayList<>();
        for (String previousList : oldPermutations) {
            for (String word : words) {
                if (previousList.contains(word)) {
                    continue;
                }
                newPermutations.add(previousList + word);
            }
        }
        oldPermutations = newPermutations;
        result.addAll(newPermutations);
    }

    return result;
}

【讨论】:

  • 成功了,按预期工作!似乎正在生成所有可能的字符串组合。谢谢你,乔尼!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 2011-12-02
  • 2012-05-17
相关资源
最近更新 更多