思路:
Trie树(字典树)。
数据量大的时候可以预先开一个全局数组存放树节点,需要的时候就分配,比每次new申请空间省时间。
实现:
1 #include <iostream> 2 #include <cstdio> 3 #include <string.h> 4 #define MAX 26 5 6 using namespace std; 7 8 struct trieNode 9 { 10 trieNode * next[MAX]; 11 int cnt; 12 }; 13 14 trieNode * createTrie() 15 { 16 trieNode * root = new trieNode(); 17 root -> cnt = 1; 18 for(int i = 0; i < MAX; i++) 19 { 20 root -> next[i] = NULL; 21 } 22 return root; 23 } 24 25 void insert(trieNode * root,char * str) 26 { 27 trieNode * tmp = root; 28 int len = strlen(str); 29 for(int i = 0; i < len; i++) 30 { 31 int index = str[i] - 'a'; 32 if(tmp -> next[index] != NULL) 33 { 34 tmp -> next[index] -> cnt ++; 35 } 36 else 37 { 38 tmp -> next[index] = createTrie(); 39 } 40 tmp = tmp -> next[index]; 41 } 42 } 43 44 int search(trieNode * root,char * str) 45 { 46 int len = strlen(str); 47 trieNode * tmp = root; 48 for(int i = 0; i < len; i++) 49 { 50 int index = str[i] - 'a'; 51 if(tmp -> next[index] != NULL) 52 { 53 tmp = tmp -> next[index]; 54 } 55 else 56 { 57 return 0; 58 } 59 } 60 return tmp -> cnt; 61 } 62 int main() 63 { 64 trieNode * root = createTrie(); 65 char tmp[11]; 66 int n, m; 67 scanf("%d", &n); 68 for(int i = 0; i < n; i++) 69 { 70 scanf("%s", tmp); 71 insert(root, tmp); 72 } 73 scanf("%d", &m); 74 for(int i = 0; i < m; i++) 75 { 76 scanf("%s", tmp); 77 printf("%d ", search(root, tmp)); 78 } 79 return 0; 80 }