字符串排列组合问题

问题:

有一个字符串(例如“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 }));
        }
    }

结果:

posted @ 2020-07-21 14:00  JackJu  阅读(484)  评论(0编辑  收藏  举报