字符串的排列

题目:输入一个字符串,打印出该字符串中字符的所有排列。例如输入字符串abc,则输出由字符abc所能排列出来的所有字符串abcacbbacbcacabcba

分析:这是一道很好的考查对递归理解的编程题,因此在过去一年中频繁出现在各大公司的面试、笔试题中。

我们以三个字符abc为例来分析一下求字符串排列的过程。首先我们固定第一个字符a,求后面两个字符bc的排列。当两个字符bc的排列求好之后,我们把第一个字符a和后面的b交换,得到bac,接着我们固定第一个字符b,求后面两个字符ac的排列。现在是把c放到第一位置的时候了。记住前面我们已经把原先的第一个字符a和后面的b做了交换,为了保证这次c仍然是和原先处在第一位置的a交换,我们在拿c和第一个字符交换之前,先要把ba交换回来。在交换ba之后,再拿c和处在第一位置的a进行交换,得到cba。我们再次固定第一个字符c,求后面两个字符ba的排列。

既然我们已经知道怎么求三个字符的排列,那么固定第一个字符之后求后面两个字符的排列,就是典型的递归思路了。

基于前面的分析,我们可以得到如下的参考代码:

 

 1 void Permutation(char* pStr, char* pBegin);

 2 

 3 /////////////////////////////////////////////////////////////////////////

 4 // Get the permutation of a string, 

 5 // for example, input string abc, its permutation is 

 6 // abc acb bac bca cba cab

 7 /////////////////////////////////////////////////////////////////////////

 8 void Permutation(char* pStr)

 9 {

10       Permutation(pStr, pStr);

11 }

12 

13 /////////////////////////////////////////////////////////////////////////

14 // Print the permutation of a string, 

15 // Input: pStr   - input string

16 //        pBegin - points to the begin char of string 

17 //                 which we want to permutate in this recursion

18 /////////////////////////////////////////////////////////////////////////

19 void Permutation(char* pStr, char* pBegin)

20 {

21       if(!pStr || !pBegin)

22             return;

23 

24       // if pBegin points to the end of string,

25       // this round of permutation is finished, 

26       // print the permuted string

27       if(*pBegin == '\0')

28       {

29             printf("%s\n", pStr);

30       }

31       // otherwise, permute string

32       else

33       {

34             for(char* pCh = pBegin; *pCh != '\0'; ++ pCh)

35             {

36                   // swap pCh and pBegin

37                   char temp = *pCh;

38                   *pCh = *pBegin;

39                   *pBegin = temp;

40 

41                   Permutation(pStr, pBegin + 1);

42 

43                   // restore pCh and pBegin

44                   temp = *pCh;

45                   *pCh = *pBegin;

46                   *pBegin = temp;

47             }

48       }

49 }

 

 

转自何海涛博客

你可能感兴趣的:(字符串)