java - 如何创建字符串的所有元音组合并将每个组合添加到 ArrayList

标签 java arrays string loops combinations

我在打印给定输入的所有元音组合时遇到问题。我的输入是“SOMETHING”,我想打印所有元音组合,例如 sxmxthxng,其中 x 是 aeiou 元音。我相信我的问题是我找到一个元音,用所有其他元音改变它,然后继续。我需要继续查看单词的其余部分,找到其他元音并更改它们,然后再继续。

其他引用

vowelList is an ArrayList containing all lower case vowels.

代码

 private static void createVowelCombos(String word) {
    Set<String> rmRepeats = new HashSet<>();
    StringBuilder sbAddWord = new StringBuilder(word);
    String[] splitWord = word.split("");

    for (int i = 0; i < word.length(); i++) {
       // System.out.println("real word: " + splitWord[i]);

        if (splitWord[i].matches(".*[aeiou]")) {
           // System.out.println("Split: " + splitWord[i]);
            for (int j = 0; j < 5; j++) {
                sbAddWord.setCharAt(i, vowelList.get(j).charAt(0));
                System.out.println(sbAddWord.toString());
            }
        }
    }
}

输入“SOMETHING”的示例输出

samething
semething
simething
something
sumething
sumathing
sumething
sumithing
sumothing
sumuthing
sumuthang
sumutheng
sumuthing
sumuthong
sumuthung

出于某种原因,它给了我所有带有“u”的组合,但没有提供其他元音。我还想获得其他元音的所有结果。

最佳答案

正如已经建议的,您的问题可以通过使用递归(带回溯)得到最好的解决。我已经修改了您的代码以便打印所需的输出。看看吧!!

private static void createVowelCombos(String word, int start) {
    StringBuilder sbAddWord = new StringBuilder(word);
    String[] splitWord = word.split("");
    if(start==splitWord.length)
    {
        System.out.println(word);
        return;
    }
    if (splitWord[start].matches(".*[aeiou]")) {
           // System.out.println("Split: " + splitWord[i]);
            for (int j = 0; j < 5; j++) {
                sbAddWord.setCharAt(start, vowelList.get(j).charAt(0));
                createVowelCombos(sbAddWord.toString(),start+1);
                //System.out.println(sbAddWord.toString());
            }
    }
    else
        createVowelCombos(sbAddWord.toString(),start+1);

}

从调用方法调用createVowelCombos("something",0)。

关于java - 如何创建字符串的所有元音组合并将每个组合添加到 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42287542/

相关文章:

javascript - 根据字符数和空格数用正则表达式拆分字符串

java - 如何将项目从netbeans中的另一个类添加到列表框

arrays - 将类型数组转换为协议(protocol)时出现 fatal error : cannot be bridged from Objective-C

arrays - 将 2d 字符串数组转换为 double swift 的 2d 数组

ios - 编码问题。转换为可读字符串

mysql - SQL 检索多维数组

java - 在 Java 上加密信息并在 Objective-C/C++/C 上解密

java - 通过在没有 SharedPreferences 的情况下使用 Google 登录自动登录

java - Jersey 中的查询参数

使用指针和数组创建随机故事生成器来处理字符串