zoukankan      html  css  js  c++  java
  • 字符串排列组合问题

    问题:

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

    结果:

  • 相关阅读:
    mybatis-cache model
    多线程开发(1)
    正则表达式(3) — 正则表达式库
    正则表达式(2) — 表达式规则
    我在迈瑞工作的两年总结
    正则表达式(1) — 常用的表达式
    C++系列(2) — 智能指针
    C++系列(1) — string
    路径去除前缀
    SIMD性能优化
  • 原文地址:https://www.cnblogs.com/jack-jun/p/13354649.html
Copyright © 2011-2022 走看看