本文介绍了字符串组合,多字符替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

According to the entered license plate (eg. ABC123) and a list of replacement values (eg 1 replaced by I). I need to get all possibles combinations.

例如:

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

输入:

预期输出:

我尝试了,但我不能...

I tried with String Combinations With Character Replacement, but I can't...

推荐答案

您可以做到使用递归,对每个字符进行迭代,然后使用原始字符和替换字符进行递归调用,如下所示:

You can do it using recursion, iterate for each character and call recursively using the original character and the replacement, something like this:

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

并按以下方式调用此方法:

And call this methods like so:

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

这篇关于字符串组合,多字符替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 00:45