一、題目:字符串的排列
題目:輸入一個字符串,打印出該字符串中字符的所有排列。例如輸入字符串abc,則打印出由字符a、b、c所能排列出來的所有字符串abc、acb、bac、bca、cab和cba。
二、解題思路
2.1 核心步驟
我們可以把一個字符串看成由兩部分組成:第一部分為它的第一個字符,第二部分是后面的所有字符。在下圖中,我們用兩種不同的背景顏色區分字符串的兩部分。
Step1.把字符串分為兩部分,一部分是字符串的第一個字符,另一部分是第一個字符以后的所有字符(有陰影背景的區域)。
Step2.接下來我們求陰影部分的字符串的排列,拿第一個字符和它后面的字符逐個交換。
2.2 代碼實現
public static void Permutation(char[] str) { if (str == null) { return; } Permutation(str, str, 0); } public static void Permutation(char[] str, char[] begin, int startIndex) { if (startIndex == str.Length) { Console.WriteLine(str); } else { for (int i = startIndex; i < str.Length; i++) { char temp = begin[i]; begin[i] = begin[startIndex]; begin[startIndex] = temp; Permutation(str, begin, startIndex + 1); temp = begin[i]; begin[i] = begin[startIndex]; begin[startIndex] = temp; } } }
三、單元測試
3.1 測試用例
(1)封裝測試輔助方法

public static void TestPortal(string str) { if (string.IsNullOrEmpty(str)) { Console.WriteLine("Test for NULL begins:"); Permutation(null); } else { Console.WriteLine("Test for {0} begins:", str); Permutation(str.ToCharArray()); } Console.WriteLine(); }
(2)功能測試、特殊輸入測試
public static void Test1() { TestPortal(null); } public static void Test2() { string str = ""; TestPortal(str); } public static void Test3() { string str = "a"; TestPortal(str); } public static void Test4() { string str = "ab"; TestPortal(str); } public static void Test5() { string str = "abc"; TestPortal(str); }
3.2 測試結果