字符串處理的方法有很多比如說Hash,Trie,但主要還是想說三叉樹,
這里有篇博文講的挺好。
Hash主要是通過一個hash函數來建立一個字符串與目標的映射,Hash函數的選擇與查找效率有很大關系,網上很多這方面的介紹。
Trie樹是一種樹狀結構,
這里有說明。當然網上還可以找到更好的介紹。其沒擴展一個節點會,會擴展出26(若是只處理普通字符,不區分大小寫)個節點,大大的浪費了存儲空間。其代碼如下:
1 const int M=26;
2 const char CH='A';
3 struct node
4 {
5 bool isend;
6 node* child[M];
7 node()
8 {
9 isend=false;
10 for(int i=0;i<M;++i)
11 child[i]=NULL;
12 }
13 };
14 node *root;
15 void Insert(char str[],node* &root)
16 {
17 if(root==NULL)
18 root=new node;
19 node* p=root;
20 int i=0;
21 while(str[i]!='\0')
22 {
23 if(p->child[str[i]-CH]==NULL)
24 p->child[str[i]-CH]=new node;
25 p=p->child[str[i]-CH];
26 ++i;
27 }
28 p->isend=true;
29 }
30 bool Seach(char str[],node* root)
31 {
32 node* p=root;
33 int i=0;
34 while(str[i]!='\0')
35 {
36 if(p->child[str[i]-CH]==NULL)
37 return false;
38 else p=p->child[str[i]-CH];
39 ++i;
40 }
41 if(p->isend) return true;
42 else return false;
43
44 }
三叉樹有trie的優點,卻又比trie占用的空間小,好像這個東西比trie更加實用,并且效率不賴,很多網站的實時補充單詞(即,輸入單詞的前綴會自動補充后半部分單詞)就是用它。三叉樹的每個節點會有一個key,左子樹,右子樹,中間子樹。查找或是插入類似于二叉樹,若是插入的數據大于key就插入左子樹,若是大于key就插入右子樹,等于key插入中間子樹(好像叫起來不順口),當然反之亦可。其具體實現代碼如下:
1 struct node
2 {
3 node* l;
4 node* r;
5 node* mid;
6 char key;
7 bool isend;
8 node():l(NULL),r(NULL),mid(NULL),isend(false),key(0){}
9 };
10 void insert(char *str,node* &root)
11 {
12 if(root==NULL)
13 {
14 root=new node;
15 root->key=str[0];
16 }
17 node* p=root;
18 node* t=p;
19 while(*str)
20 {
21 if(*str>p->key)
22 {
23 if(p->r==NULL)
24 {
25 p->r=new node;
26 p->r->key=*str;
27 }
28 p=p->r;
29 }
30 else if(*str<p->key)
31 {
32 if(p->l==NULL)
33 {
34 p->l=new node;
35 p->l->key=*str;
36 }
37 p=p->l;
38 }
39 else
40 {
41 ++str;
42 if(*str=='\0') break;
43 if(p->mid==NULL)
44 {
45 p->mid=new node;
46 p->mid->key=*str;
47 }
48 p=p->mid;
49 }
50 }
51 p->isend=true;
52 }
53 bool search(char *str,node* root)
54 {
55 while(*str)
56 {
57 if(*str> root->key)
58 {
59 root=root->r;
60 }
61 else if(*str<root->key)
62 {
63 root=root->l;
64 }
65 else
66 {
67 ++str;
68 if(*str!='\0')
69 root=root->mid;
70 }
71 if(root==NULL) return false;
72 }
73 if(root->isend) return true;
74 else return false;
75 }