zoukankan      html  css  js  c++  java
  • 剑指Offer面试题:26.字符串的排列

    一、题目:字符串的排列

    题目:输入一个字符串,打印出该字符串中字符的所有排列。例如输入字符串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();
        }
    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 测试结果

  • 相关阅读:
    hdu 6702 ^&^ 位运算
    hdu 6709 Fishing Master 贪心
    hdu 6704 K-th occurrence 二分 ST表 后缀数组 主席树
    hdu 1423 Greatest Common Increasing Subsequence 最长公共上升子序列 LCIS
    hdu 5909 Tree Cutting FWT
    luogu P1588 丢失的牛 宽搜
    luogu P1003 铺地毯
    luogu P1104 生日
    luogu P1094 纪念品分组
    luogu P1093 奖学金
  • 原文地址:https://www.cnblogs.com/edisonchou/p/4796317.html
Copyright © 2011-2022 走看看