C#重新排列字符串中的字符的算法

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

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

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

这是一个经常被问到的问题。 尝试搜索“排列”,你会发现很多关于如何用各种语言做到这一点的好答案。

C#中有一个排列和组合算法库:

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

我还在EvenMoreLinq分支中为Google Code上的MoreLinq项目提供了运营商。 如果您只是对如何实现算法感到好奇,可以在此处查看Permutations()的代码 。

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

您还可以在同一代码库中找到其他组合操作( 子集 , 置换 子集 , 笛卡尔 积 , 随机子集 , 切片 , 分区等)的算法。

以下是使用MoreLinq扩展来置换序列的方法。 因此,例如,您可以置换一个字符串(被视为一系列char ),如下所示:

 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) ); } 
 static void Main(string[] args) { Console.WriteLine("Enter String:"); string inputString = Console.ReadLine(); Console.WriteLine(); List lstAnagrams = new List(); 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 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; }