4

特定の文字をアスタリスクに置き換える必要がある単語がありますが、この単語から置き換えられたすべてのバリエーションを取得する必要があります。たとえば。次の文字「e」をアスタリスクに置き換えたい:

String word = telephone;

しかし、結果としてこのリストを取得するには:

List of words = [t*lephone, tel*phone, telephon*, t*l*phone, t*lephon*, tel*phon*, t*l*phon*];

Javaでこれを行う簡単な方法はありますか?

4

1 に答える 1

5

次のコードは、再帰的な方法でそれを行います。

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

于 2013-03-26T17:14:24.973 に答える