替换某些字符的所有出现并获取所有变体

问题描述:

我有一个词,我需要用星号替换某个字符,但我需要从该单词中获取所有替换的变体。例如。我想用星号来代替字符“E”:替换某些字符的所有出现并获取所有变体

String word = telephone; 

但要获得这个名单的结果:

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

是否有一个快速的方式在Java中做到这一点?

+0

我不这么认为。我建议做一个简单的递归算法(DFS)。 – Martinsos 2013-03-26 17:00:43

下面的代码将做到这一点在递归的方式:

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与原始单词。