我用字典树写的 按照题意做就行
#include<iostream> #include<cstring> #include<cstdio> using namespace std; class trie { public: trie* next[26]; char str_temp[12]; int num; //记录前缀的个数 bool value; //标记这里是不是一个单词 trie() { for(int i=0; i<26; i++) next[i]=0; value=0; num=0; } } root; void insert(trie* p,char* s,char* s1) { p=&root; int k=0; while(s[k]!='\0') { if(!p->next[s[k]-'a']) p->next[s[k]-'a']=new trie; p=p->next[s[k]-'a']; p->num++; k++; } p->value=1; strcpy(p->str_temp,s1); // cout<<p->str_temp<<endl; } //查找 int find(trie* p,char* s) { p=&root; int k=0; while(s[k]!='\0'&&p->next[s[k]-'a']) { p=p->next[s[k]-'a']; k++; } // cout<<endl<<"test"<<" "<<k<<" "<<strlen(s)<<endl; if(p->value&&s[k]=='\0') //我少了s[k]=='\0'这个WA了8次 { printf("%s",p->str_temp); return 1; } return 0; } int main() { char str[12],str1[12],cstr[3010],astr[12]; trie *p=&root; while(scanf("%s",str)!=EOF&&strcmp(str,"END")!=0) { if(!strcmp(str,"START")) continue; scanf("%s",str1); insert(p,str1,str); } getchar(); while(gets(cstr)&&strcmp(cstr,"END")!=0) { if(!strcmp(cstr,"START")) continue; memset(astr,'\0',sizeof(astr)); for(int i=0,j=0;cstr[i]!='\0';i++) { if(cstr[i]<='z'&&cstr[i]>='a') { astr[j]=cstr[i]; j++; } else { int m=find(p,astr); if(!m) printf("%s",astr); printf("%c",cstr[i]); if(j) { memset(astr,'\0',sizeof(astr)); j=0; } } } printf("\n"); } return 0; }