剑指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(); }
(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 测试结果
分类:
【012】计算机专业基础
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?