題目地址:http://ac.jobdu.com/problem.php?cid=1039&pid=11
字串的排序
時間限制:1 秒 記憶體限制:32 兆
-
題目描述:
-
輸入一個字串,按字典序列印出該字串中字元的所有排列。例如輸入字串abc,則列印出由字元a,b,c所能排列出來的所有字串abc,acb,bac,bca,cab和cba。
-
輸入:
-
每個測試案例包括1行。
輸入一個字串,長度不超過9(可能有字元重複),字元只包括大小寫字母。
-
輸出:
-
對應每組資料,按字典序輸出所有排列。
-
範例輸入:
-
abc
BCA
-
範例輸出:
-
abc
acb
bac
bca
cab
cba
ABC
ACB
BAC
BCA
CAB
CBA
思路:1、找出給定字串的所有排列;
2、對所有排列進行字典排序;
3、去除重複排列,輸出答案。
注意:1、必須要去除重複排列,比如輸入aab,排序有6種可能:aab,aba,aab,aba,baa,baa;去除重複之後,為3種可能,aab,aba,baa。若不然的話,會判wrong answer。
2、 此題若用C++stl的next_permutation函數,則會逾時,所以要自己寫全排列的代碼。
代碼如下:
#include <stdio.h>#include <stdlib.h>#include <string.h>int cmp( const void *a, const void *b ){char* s1 = (char *)a;char* s2 = (char *)b;return strcmp(s1, s2);}void permutation(char* pStr, char* pBegin);char s[362890][11];int count;int main(){char str[11],temp[11];int n,f,i;while(scanf("%s",str)!=-1){count = 0;n = strlen(str);permutation(str,str); //找出str的所有排列f = 1;for(i=1;i<=n;i++)f = f*i;qsort(s,f,11*sizeof(char),cmp); //對所有的排列按字典序排序strcpy(temp,"\0");for(i=0;i<f;i++)if(strcmp(temp,s[i])) //去除重複的排列{strcpy(temp,s[i]);printf("%s\n",s[i]);}}return 0;}//找出字串的所有排列,並沒有按字典序//此段代碼出自何海濤的《劍指offer》void permutation(char* pStr, char* pBegin){if(*pBegin == '\0'){strcpy(s[count],pStr);count++;}else{for(char* pCh = pBegin; *pCh!='\0'; pCh++ ){char temp = *pCh;*pCh = *pBegin;*pBegin = temp;permutation(pStr,pBegin+1);temp = *pCh;*pCh = *pBegin;*pBegin = temp;}}}