c# - 具有多字符替换的字符串组合

标签 c# algorithm combinations

根据输入的车牌(例如ABC123)和替换值列表(例如1替换为I)。我需要获得所有可能的组合。

例如:

1 => I
3 => B
A => H
0 (zero) => O
O => 0 (zero)

输入:

ABC123

预期输出:

ABC123, ABCI23, ABCI28, ABC128, HBC123, HBCI23, HBCI28, HBC128

我试过 String Combinations With Character Replacement , 但我不能...

最佳答案

您可以使用递归来完成,对每个字符进行迭代并使用原始字符和替换字符递归调用,如下所示:

public static IEnumerable<string> Combinations(string s, Dictionary<char, char> replacements)
{
    return Combinations(s, replacements, 0, string.Empty);
}

private static IEnumerable<string> Combinations(string original, Dictionary<char, char> replacements, int index, string current)
{
    if (index == original.Length) yield return current;
    else
    {
        foreach (var item in Combinations(original, replacements, index + 1, current + original[index]))
            yield return item;

        if (replacements.ContainsKey(original[index]))
            foreach (var item in Combinations(original, replacements, index + 1, current + replacements[original[index]]))
                yield return item;
    }
}

然后像这样调用这个方法:

Dictionary<char, char> dict = new Dictionary<char,char>();
dict['1'] = 'I';
dict['3'] = 'B';
dict['A'] = 'H';
dict['O'] = '0';
dict['0'] = 'O';

var combs = Combinations("ABC123", dict);

关于c# - 具有多字符替换的字符串组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36901535/

相关文章:

c# - 如何在控制台的同一行上从整数打印文本和值?

C# TypeConverter.ConvertFrom() 问题

algorithm - 根据网格划分的距离图放置点

python - 如何将字符串字典转换为列表到字典列表?

c# - 为什么扩展方法中的 `char` 参数被解释为 `int` ?

c# - 通过ajax调用 Controller 方法到达 "404 not found"

C++ 标准库方法删除列表中满足条件的一对项目中的一个

algorithm - 给定一个二维数组,找到簇

r - 添加条件以在 R 中扩展网格?

c# - 在 C# 中获取 List<List<int>> 的所有组合(也包含部分结果)