1. 程式人生 > 實用技巧 >字串排列組合問題

字串排列組合問題

問題:

有一個字串(例如“abcd”),需要對字串內部進行排列組合,組合的要求有兩個,一個是必須按照順序,第二個是必須是三個字母的。

例如可以得到下面的結果。

abc,abd,acd,bcd。

先加下處理這種問題的思路。

首先,我們需要得到所有三個字母的所有排列組合。

其次,我們需要三個字母的排列組合進行內部的排序,用Array.Sort方法進行排序。

最後,我們會得到許多重複的元素,這時候我們可以用list.Distinct方法來去重。

下面是具體的程式碼。

 class Program
    {
        static void Main(string[] args)
        {
            
string a = "abcd"; var m = a.ToCharArray().AsEnumerable(); IEnumerable<IEnumerable<char>> result = GetPermutations(m, 3); char [] b; string newstring; List<string> list = new List<string>();
foreach (var item in result) { b = item.ToList().ToArray(); Array.Sort(b); newstring = new string(b); list.Add(newstring); } list = list.Distinct().ToList() ; list.ForEach(s => Console.WriteLine(s)); Console.ReadKey(); }
static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> list, int length) { if (length == 1) return list.Select(t => new T[] { t }); return GetPermutations(list, length - 1) .SelectMany(t => list.Where(e => !t.Contains(e)), (t1, t2) => t1.Concat(new T[] { t2 })); } }

結果: