我在打印给定输入的所有元音组合时遇到问题。我的输入是“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/