編程珠璣–第二章變位詞程式的實現

來源:互聯網
上載者:User

題目描述:給定一個英語字典,找出其中的所有變位詞集合。例如,“pots”、“stop”、“tops”互為變位詞,因為每一個單詞都可以通過改變其他單詞中的字母的順序來得到。

程式主要有三部分組成,sign、sort和squash。我們用來說明(假設要處理的單詞有六個pans pots opt snap stop tops),處理結果如下:

可見sign是將單詞進行排序(將pans排成anps,按照字母序),sort是對排好序的所有單詞再進行一次排序,程式碼如下: 

#include<stdio.h>#include<stdlib.h>#include<algorithm>#define MAXWORDNUM 100000#define MAXWORDLEN 100using namespace std;struct word_all{char word[MAXWORDLEN];char sig[MAXWORDLEN];};word_all all[100000];bool cmp(word_all a,word_all b){if(strcmp(a.sig,b.sig)<0)return 1;return 0;}int main(){int num=0;while(scanf("%s",all[num].word)!=EOF){strcpy(all[num].sig,all[num].word);sort(all[num].sig,all[num].sig+strlen(all[num].sig));num++;}sort(all,all+num,cmp);//列印經過處理過的資料//for(int i=0;i<num;i++){//printf("%s %s\n",all[i].sig,all[i].word);//}//輸出int linenum=0;char oldsig[MAXWORDLEN];strcpy(oldsig,"");for(int j=0;j<num;j++){if(strcmp(oldsig,all[j].sig)!=0&&linenum>0)printf("\n");strcpy(oldsig,all[j].sig);linenum++;printf("%s ",all[j].word);}return 0;}

輸出結果為:

一個小插曲:編程珠璣上寫的比較單詞大小的函數int charcomp(char *x,char *y){return *x - *y};

這種函數應用到sort最後一個參數中是不行的,第一點:首先因為數組是char類型的,應該使用char x,char y;

第二點:由於最後一個比較函數是bool類型的,x-y比如說x=3,y=4,不管x-y還是y-x返回都不等於零,返回的為true,所以是不能作為比較條件的。應該改為 return x<y。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.