【问题标题】:C# Algorithm that Re-arranges Chars in a String重新排列字符串中的字符的 C# 算法
【发布时间】:2011-04-15 08:22:44
【问题描述】:

我想要一个 C# 算法,它可以在长度动态的字符串中重新排列字符。找不到一个,我知道肯定有一个。

算法必须重新排列元素以在所有可能的组合中形成新的字符串。

例如,“cat”会产生以下内容:
cat cta tca tac act atc

【问题讨论】:

标签: c# algorithm string permutation


【解决方案1】:

这是一个相当常见的问题。尝试搜索“排列”,您会发现很多关于如何在各种语言中执行此操作的好答案。

这里有一个 C# 中的排列组合算法库:

http://www.codeproject.com/KB/recipes/Combinatorics.aspx

【讨论】:

    【解决方案2】:

    还有我贡献给MoreLinq project on Google Code的算子在EvenMoreLinq分支。如果你只是好奇算法是如何实现的,可以看code for Permutations<T>() here

    它们旨在与 LINQ 很好地融合,并同时使用延迟和流式评估。排列是一个有趣的排列,因为生成所有排列是一个N! 操作......即使N 的值很小,它也会变得非常大。根据您生成排列的方式,您可能(也可能不)能够实际枚举所有排列。

    您还可以在同一代码库中找到其他组合运算(SubsetsPermutedSubsetsCartesian ProductsRandom SubsetsSlicesPartitions 等)的算法。

    这里介绍了如何使用 MoreLinq 扩展来置换序列。例如,您可以按如下方式排列一个字符串(被视为chars 的序列):

    using MoreLinq;
    
    string input = "cat";
    var permutations = input.Permutations();
    
    foreach( var permutation in permutations )
    {
        // 'permutation' is a char[] here, so convert back to a string
        Console.WriteLine( new string(permutation) ); 
    }
    

    【讨论】:

      【解决方案3】:
      static void Main(string[] args)
      {
          Console.WriteLine("Enter String:");
          string inputString = Console.ReadLine();
          Console.WriteLine();
          List<string> lstAnagrams = new List<string>();
          int numAnagram = 1;
      
          permute(inputString.ToCharArray(), 0, inputString.Length - 1, lstAnagrams);
          foreach(string anagram in lstAnagrams)
          {
              Console.WriteLine(numAnagram.ToString() + " " + anagram);
              numAnagram++;
          }
      
          Console.ReadKey();
      }
      
      static void permute(char[] word, int start, int end, List<string> lstAnagrams)
      {
          if (start == end)
              lstAnagrams.Add(string.Join("", word));
          else
          {
              for (int position = start; position <= end; position++)
              {
                  swap(ref word[start], ref word[position]);
                  permute(word, start + 1, end,lstAnagrams);
                  swap(ref word[start], ref word[position]);
              }
          }
      }
      
      static void swap(ref char a, ref char b)
      {
          char tmp;
          tmp = a;
          a = b;
          b = tmp;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多