【问题标题】:Get permutation of specific characters in strings获取字符串中特定字符的排列
【发布时间】:2017-04-05 07:40:14
【问题描述】:

给定一个像“N00MNM”这样的字符串,我需要字符串内所有零'0'字符的排列,以固定顺序维护所有其他字符。

结果必须是:

“N0M0NM”“N0MN0M”“N0MNM0”“NM00NM”“NM0N0M”“NM0NM0”“NMN0M0”“NMNM00” "0N0MNM" "0NM0NM" "0NMN0M" "0NMNM0"

标准置换函数完成这项工作需要太多时间(我们谈论的是大约 1500 毫秒),并且要测试的字符串比示例字符串长。

有算法吗?

【问题讨论】:

  • 允许多少个0?初始字符串中给出的总数?
  • 如果你的代码需要 1.5 秒来做 12 次组合.. 你需要看看你的代码做了什么

标签: c# string permutation


【解决方案1】:

您可以通过获取可以放置字符0(在本例中)的所有不同位置然后包括0 字符总数(在本例中为00 ) 在字符串的所有位置。这些位置取自没有出现所有0 的字符串。下面的代码就是这样做的:

public static IEnumerable<string> Combs(string str, char c)
{
    int count = str.Count(_c => _c == c);
    string _str = new string(str.Where(_c => _c != c).ToArray());

    // Compute all combinations with different positions
    foreach (var positions in GetPositionsSets(0, _str.Length, count))
    {
        StringBuilder _b = new StringBuilder();
        int index = 0;
        foreach (var _char in _str)
        {
            if (positions.Contains(index))
            { _b.Append($"{c}{_char}"); }
            else
            { _b.Append(_char); }
            index++;
        }
        if (positions.Contains(index))
            _b.Append(c);
        yield return _b.ToString();
    }
    //Compute the remaining combinations. I.e., those whose at some position
    //have the amount of supplied characters.
    string p = new string(c, count);
    for (int i = 0; i < _str.Length; i++)
    {
        yield return _str.Insert(i, p);
    }
    yield return _str + p;
}

//Gets all posible positions sets that can be obtain from minPos 
//until maxPos with positionsCount positions, that is, C(n,k) 
//where n = maxPos - minPos + 1 and k = positionsCount
private static IEnumerable<HashSet<int>> GetPositionsSets(int minPos, int maxPos, int positionsCount)
{
    if (positionsCount == 0)
        yield return new HashSet<int>();

    for (int i = minPos; i <= maxPos; i++)
    {
        foreach (var positions in GetPositionsSets(i + 1, maxPos,     positionsCount - 1))
        {    
            positions.Add(i);
            yield return positions;
        }
    }
}

"N00MNM" 上面代码的输出是:

0N0MNM
0NM0NM
0NMN0M
0NMNM0
N0M0NM
N0MN0M
N0MNM0
NM0N0M
NM0NM0
NMN0M0
00NMNM
N00MNM
NM00NM
NMN00M
NMNM00

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-20
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    相关资源
    最近更新 更多