2010-09-21 68 views
3

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

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

例如, “猫” 将产生如下:
猫CTA TCA TAC行为ATC

+0

你查看常见问题解答:因此,例如,可以按如下方式置换一个字符串(被视为的char个序列)? http://stackoverflow.com/tags/algorithm/faq – 2010-09-21 20:06:28

回答

6

也有我的EvenMoreLinq跳转到MoreLinq project on Google Code贡献了运营商。如果您只是对算法的实现感到好奇,您可以看到code for Permutations<T>() here

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

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

下面介绍如何使用MoreLinq扩展来排列序列。

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