题目:输入一个字符串,打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a、b、c所能排列出来的所有字符串abc、acb、bac、bca、cab和cba。
我们可以把一个字符串看成由两部分组成:第一部分为它的第一个字符,第二部分是后面的所有字符。在下图中,我们用两种不同的背景颜色区分字符串的两部分。
Step1.把字符串分为两部分,一部分是字符串的第一个字符,另一部分是第一个字符以后的所有字符(有阴影背景的区域)。
Step2.接下来我们求阴影部分的字符串的排列,拿第一个字符和它后面的字符逐个交换。
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;
}
}
}
(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);
}
作者:周旭龙
出处:http://edisonchou.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。