【劍指offer】【九度oj】字串的排序

來源:互聯網
上載者:User

題目地址: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;}}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.