打印出给定字符串中字符的所有不重复排列

来源:互联网 发布:网红张大奕的淘宝店 编辑:程序博客网 时间:2024/05/17 00:03
<big>今天真是有点小郁闷,笔试居然没通过,题目就是上面这个,看着并不太难,但是可能是有点紧张吧,想了至少三四十分钟居然还没理清思路。笔试结束之后特意跑到星巴克静下心来思考了一下,结果用了二十分钟左右就写出来了(咳咳,大神请绕道)。

再复述一遍题目吧:
给定一个字符串,打印出该字符串所有字符的不重复排列。
例如:字符串abc的排列包括abc,bac,cab等

乍一看真是不难,也不知道当时怎么脑子就宕机了,完全理不清头绪。
下面给出C#解法。

        public static void PrintPermutation (string str) {            char[] charArr = str.ToCharArray ();            List<char> chars = new List<char> (charArr);            chars.Sort ();  //这是不重复的关键,用来判断相邻字符是否相同            List<char> toPrintCharList = new List<char> ();            PrintPermutationRecursive (chars, toPrintCharList);        }        private static void PrintPermutationRecursive (List<char> chars, List<char> toPrintCharList) {            for (int i = 0; i < chars.Count; i++) {                // 与前一字符相同则跳过本层                if (i > 0 && chars [i] == chars [i - 1])                        continue;                char toPrintChar = chars [i];                chars.RemoveAt (i);                toPrintCharList.Add(toPrintChar);                PrintPermutationRecursive (chars, toPrintCharList);                // 所有字符都已经加入到toPrintCharList时就打印出来                if (chars.Count == 0) {                     for (int j = 0; j < toPrintCharList.Count; j++) {                        Console.Write (toPrintCharList [j] + " ");                    }                    Console.WriteLine ();                }                chars.Insert (i, toPrintChar);                toPrintCharList.RemoveAt (toPrintCharList.Count - 1);            }        }

平时感觉自己还挺能保持冷静的,也不知道怎么一到关键时刻就冷静不下来呢,简直气死了。

其实这一道算法题完全撑不住一篇博客,但写在这里当做对自己的鞭策吧。

阅读全文
0 0