纵有疾风起
人生不言弃

剑指Offer面试题:26.字符串的排列

一、题目:字符串的排列

题目:输入一个字符串,打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a、b、c所能排列出来的所有字符串abc、acb、bac、bca、cab和cba。

二、解题思路

2.1 核心步骤

  我们可以把一个字符串看成由两部分组成:第一部分为它的第一个字符,第二部分是后面的所有字符。在下图中,我们用两种不同的背景颜色区分字符串的两部分。

剑指Offer面试题:26.字符串的排列插图

  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)封装测试辅助方法

剑指Offer面试题:26.字符串的排列插图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();    }

View Code

  (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 测试结果

剑指Offer面试题:26.字符串的排列插图3

 

文章转载于:https://www.cnblogs.com/edisonchou/p/4796317.html

原著是一个有趣的人,若有侵权,请通知删除

未经允许不得转载:起风网 » 剑指Offer面试题:26.字符串的排列
分享到: 生成海报

评论 抢沙发

评论前必须登录!

立即登录