Question

I have a word on which I need to replace a certain character with an asterisk, but I need to get all the replaced variations from this word. For eg. I want to replace character 'e' with an asterisk in:

String word = telephone;

but to get this list as a result:

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

Is there a quick way to do this in Java?

Was it helpful?

Solution

The following code will do that in a recursive way:

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;
}

It adds the original String to the output, so:

public static void main(String[] args) {
    String word = "telephone";
    System.out.println(getPermutations(word, 'e'));
}

Outputs:

[telephone, t*lephone, tel*phone, t*l*phone, telephon*, t*lephon*, tel*phon*, t*l*phon*]

But you can always call remove on the returned Set with the original word.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top