1、insert : 往神奇字典中插入一個單詞
2、delete: 在神奇字典中刪除所有前綴等於給定字符串的單詞
3、search: 查詢是否在神奇字典中有一個字符串的前綴等於給定的字符串
5 insert hello insert hehe search h delete he search helloSample Output
Yes No
#include <iostream> #include <stdio.h> #include<string.h> #include<algorithm> using namespace std; struct Trie { Trie *next[27]; int v; Trie() { for(int i=0; i<27; i++) next[i]=NULL; v=0; } }; void insert (char *str,Trie *root) { //cout <<"______________1111111______________"<<endl; int m; Trie *p; p=root;//cout<<"adsadadasda "<<p->v<<endl; for(int i=0;str[i]; i++) { m=str[i]-'a'; if(p->next[m]==NULL) { (p->next[m])=new Trie; //cout<<"-------"<<i<<endl; } ((p->next[m])->v)++;//cout<<"----------------"<<bool(p->next['l'-97])<<endl; p=(p->next[m]); } } int quere(char *str,Trie *root) { int m,i; Trie *p; p=root; for(i=0;str[i ]; i++) { m=str[i]-'a'; //cout <<"______________****222222______________"<<endl; // cout<<(q->v)<<endl; if(p->next[m]==NULL) { return 0; } //cout <<"______________222222______________"<<endl; p=p->next[m]; } return 1; } int del(char *str,Trie *root) { int len=strlen(str); //cout <<"______________3333333______________"<<endl; int m,i,k; Trie *p,*q; p=root;q=root; for(i=0; str[i]; i++) { m=str[i]-'a'; if(p->next[m]==NULL) { return 0; } if(i==len-1) { k=p->next[m]->v; } p=p->next[m]; } for(i=0; str[i]; i++) { m=str[i]-'a'; if(q->next[m]==NULL) { return 0; } (q->next[m]->v)=(q->next[m]->v)-k; if((q->next[m]->v)<1) { q->next[m]=NULL; return 0; } if(i==len-1) { q->next[m]=NULL; } q=q->next[m]; } return 0; } /*void show(Trie *root,int j=0) { for(int i=0; i<=25; i++) if(root->next[i]!=NULL){ cout<<j<<"--------"<<char(i+97)<<endl; show(root->next[i],j+1); } }*/ int main() { Trie *root; char a[10],str[25]; int n; while(scanf("%d",&n)!=EOF) { root=new Trie; while(n--) { scanf("%s%s",a,str); (root->v)=1; if(strcmp(a,"insert")==0) { insert(str,root); // show(root); } if(strcmp(a,"search")==0) { int b=quere(str,root); // cout <<"______________444444______________"<<endl; if(b) { // cout <<"______________555555______________"<<endl; printf("Yes\n"); } else printf("No\n"); } if(strcmp(a,"delete")==0) del(str,root); //show(root); } } return 0; }