次のコードは、再帰的な方法でそれを行います。
public static Set<String> getPermutations(final String string, final char c) {
final Set<String> permutations = new HashSet<>();
final int indexofChar = string.indexOf(c);
if (indexofChar <= 0) {
permutations.add(string);
} else {
final String firstPart = string.substring(0, indexofChar + 1);
final String firstPartReplaced = firstPart.replace(c, '*');
final String lastPart = string.substring(indexofChar + 1, string.length());
for (final String lastPartPerm : getPermutations(lastPart, c)) {
permutations.add(firstPart + lastPartPerm);
permutations.add(firstPartReplaced + lastPartPerm);
}
}
return permutations;
}
String
オリジナルを出力に追加するので、次のようになります。
public static void main(String[] args) {
String word = "telephone";
System.out.println(getPermutations(word, 'e'));
}
出力:
[telephone, t*lephone, tel*phone, t*l*phone, telephon*, t*lephon*, tel*phon*, t*l*phon*]
しかし、あなたはいつでも元の言葉でremove
返されたものを呼び出すことができます。Set