【问题标题】:Next permutation algorithm c# and linq [closed]下一个排列算法 c# 和 linq [关闭]
【发布时间】:2019-07-10 05:30:17
【问题描述】:

我需要一个函数来查找字符串的下一个字典值(字符串的长度不应该改变)。例如(abc=>acbaaba=>abaa

【问题讨论】:

标签: c# linq permutation


【解决方案1】:

您可以尝试以下代码,它使用私有字段来查找由查找排列的方法生成的所有排列:

private static List<string> _permutations = new List<string>();
public static Main(string[] args)
{
  string testString = "abc";
  TestMethod(testString);
  // You need to handle case when you have last permuation in a list
  string nextPermutation = _permutations[_permutations.IndexOf(testString) + 1];
}

private static void Swap(ref char a, ref char b)
{
  if (a == b) return;

  a ^= b;
  b ^= a;
  a ^= b;
}

private static void GetPer(char[] list)
{
  int x = list.Length - 1;
  GetPer(list, 0, x);
}

private static void GetPer(char[] list, int k, int m)
{
  if (k == m)
  {
    _permutations.Add(new string(list));
  }
  else
    for (int i = k; i <= m; i++)
    {
      Swap(ref list[k], ref list[i]);
      GetPer(list, k + 1, m);
      Swap(ref list[k], ref list[i]);
    }
}

private static void TestMethod(string str)
{
  char[] arr = str.ToCharArray();
  GetPer(arr);
}

【讨论】:

    猜你喜欢
    • 2014-11-06
    • 1970-01-01
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 1970-01-01
    相关资源
    最近更新 更多