C#学习笔记:生成字符串的全排列

来源:互联网 发布:易语言断网瞬移源码 编辑:程序博客网 时间:2024/06/07 20:42

问题描述:

根据输入的字符串,对字符串进行全排列,输出所有字符串。

例如,输入"ab",输出"ab", "ba";输入"abc",输出"abc", "acb", "bac", "bca", "cab", "cba"。


代码:

        static void Main()        {            string word = Console.ReadLine();            while (!string.IsNullOrEmpty(word))            {                foreach (var item in getFullPermutation(word))                {                    Console.Write(item + ", ");                }                Console.WriteLine();                word = Console.ReadLine();            }        }        static IEnumerable<string> getFullPermutation(string word)        {            if (word.Length < 2) yield return word;            else            {                char current = word[0];                foreach (var item in getFullPermutation(word.Substring(1)))                {                    char[] tmp = new char[word.Length];                    for (int i = 0; i < item.Length; i++)                        tmp[i] = item[i];                    tmp[word.Length - 1] = current;                    for (int i = item.Length; i >= 0; i--)                    {                        if (i < item.Length)                        {                            tmp[i + 1] = tmp[i];                            tmp[i] = current;                        }                        string result = string.Empty;                        for (int j = 0; j < tmp.Length; j++)                            result += tmp[j];                        yield return result;                    }                }            }        }


0 0
原创粉丝点击