问题:http://hihocoder.com/problemset/problem/1014
给定一个字符串字典dict,输入字符串str, 要求从dict中找出所有以str为前缀的字符串个数。
构建Trie树:
1) 一个节点有多个子节点。用vector<Node*> nexts 存储。
2) 两个字符串的相同前缀部分共用同一条路径。
3) 每个节点包含计数变量 cnt, 表示有多少个字符串共用该节点
复杂度分析:
假定dict中的字符串个数 n, 字符串的长度 l
1)建树:O(n^2*l)
2) 查找:O(n*l)
源码:
1 #include <iostream> 2 #include <vector> 3 #include <string> 4 using namespace std; 5 6 //node structure in Trie tree 7 struct Node 8 { 9 Node(char _chr = -1){chr = _chr; cnt = 0;} 10 char chr; 11 vector<Node*> nexts; 12 int cnt;//how many strings pass current node 13 }; 14 15 int main() 16 { 17 Node* root = new Node;//root of dictornary 18 Node* current; 19 vector<Node*> v_current; 20 int cnt, vsize, i, j, strLen; 21 string str; 22 23 //create Trie tree 24 cin>>cnt; 25 while(cnt-- > 0) 26 { 27 cin>>str; 28 strLen = str.length(); 29 current = root; 30 for(i = 0; i < strLen; i++) 31 { 32 v_current = current->nexts; 33 vsize = v_current.size(); 34 //try to find str[i] in current tree 35 for(j = 0; j < vsize; j++) 36 { 37 if(v_current[j]->chr == str[i]) 38 break; 39 } 40 if(j == vsize)//not found, create a new node 41 { 42 Node* tmp = new Node(str[i]); 43 current->nexts.push_back(tmp); 44 } 45 current = current->nexts[j]; 46 current->cnt++;//increase count of current node 47 } 48 } 49 50 cin>>cnt; 51 while(cnt-- > 0) 52 { 53 cin>>str; 54 strLen = str.length(); 55 current = root; 56 for(i = 0; i < strLen; i++) 57 { 58 v_current = current->nexts; 59 vsize = v_current.size(); 60 for(j = 0; j < vsize; j++) 61 if(v_current[j]->chr == str[i]) 62 break; 63 if(j == vsize)//not found 64 { 65 cout<<'0'<<endl; 66 break; 67 } 68 current = v_current[j]; 69 } 70 if(i == strLen) 71 cout<<current->cnt<<endl; 72 } 73 return 0; 74 }