【问题标题】:Replace all occurences of certain char and get all variations替换所有出现的特定字符并获得所有变体
【发布时间】:2013-03-16 14:24:41
【问题描述】:

我有一个单词需要用星号替换某个字符,但我需要从这个单词中获取所有替换的变体。例如。我想用星号替换字符'e':

String word = telephone;

但是要得到这个列表作为结果:

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

在 Java 中有没有快速的方法来做到这一点?

【问题讨论】:

  • 我不这么认为。我建议做一个简单的递归算法(DFS)。

标签: java string replace variations


【解决方案1】:

以下代码将以递归方式执行此操作:

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*]

但您始终可以在返回的Set 上使用原始单词调用remove

【讨论】:

    猜你喜欢
    • 2014-10-27
    • 1970-01-01
    • 2019-01-10
    • 2018-07-11
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    相关资源
    最近更新 更多