Trie树又称单词查找树,多应用与搜索引擎或者输入法的词频统计,利用字符串的公共前缀加快查找速度。

第一次接触,不过代码还是比较好写的。

Impl:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <string>
 4 
 5 struct TrieTree
 6 {
 7     int count;
 8     TrieTree* word[26];
 9     TrieTree()
10     {   
11         count = 0;
12         for (int i = 0; i < 26; ++i) word[i] = NULL;
13     }   
14 };
15 
16 void buildTrie(const char* word, TrieTree* trieTree)
17 {
18     int i = 0;
19     while (word[i] != '\0')
20     {   
21         int index = word[i] - 'a';
22         if (!trieTree->word[index])
23             trieTree->word[index] = new TrieTree();
24         trieTree = trieTree->word[index];
25         trieTree->count++;
26         i++;
27     }   
28 }
29 
30 int queryTrie(const char* word, TrieTree* trieTree)
31 {
32     int i = 0;
33     while (word[i] != '\0' && trieTree)
34     {   
35         trieTree = trieTree->word[word[i] - 'a'];
36         i++;
37     }   
38     if(!trieTree) return 0;
39     else return trieTree->count;
40 }
41 
42 char word[20];
43 int main()
44 {
45     int n;
46     scanf("%d", &n);
47     TrieTree* root = new TrieTree();
48     while (n--)
49     {
50         scanf("%s", word);
51         buildTrie(word, root);
52     }
53 
54     scanf("%d", &n);
55     while (n--)
56     {
57         scanf("%s", word);
58         printf("%d\n",queryTrie(word, root));
59     }
60 
61     return 0;
62 }
View Code