下一个排列算法 c# 和 linq



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

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

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

最新更新