#include <iostream>
#include <vector>
using namespace std;
const int NodeMax = 26;
typedef struct _TrieNode {
int cnt;
struct _TrieNode* next[NodeMax];
}TrieNode;
TrieNode* createTrie() {
TrieNode* root = NULL;
root = (TrieNode*)malloc(sizeof(TrieNode));
if(root == NULL) {
return NULL;
}
root->cnt = 1;
for(int i=0;i<NodeMax;++i) {
root->next[i] = NULL;
}
return root;
}
void insertTrieNode(TrieNode* root, string word) {
TrieNode* p = root;
for(int i=0;i<word.length();++i) {
int k = word[i] - 'a';
if(p->next[k]) {
p->next[k]->cnt++;
} else {
p->next[k] = createTrie();
}
p = p->next[k];
}
}
int searchPrefix(TrieNode* root, string word) {
TrieNode* p = root;
for(int i=0;i<word.length();++i) {
int k = word[i] - 'a';
if(p->next[k] == NULL)
return 0;
p = p->next[k];
}
return p->cnt;
}
int main(int argc, char* argv[]) {
int M=0;
cin >> M;
TrieNode* root = createTrie();
for(int i=0;i<M;++i) {
string tmp;
cin >> tmp;
insertTrieNode(root, tmp);
}
cin >> M;
for(int i=0;i<M;++i) {
string tmp;
cin >> tmp;
cout << searchPrefix(root, tmp) << endl;
}
return 0;
}
Created
August 14, 2016 09:33
-
-
Save guiyang882/cbf38ca38221837d816d55b9350aadbd to your computer and use it in GitHub Desktop.
使用C++创建TrieTree数据结构,也就是所说的字典树结构!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
5
babaab
babbbaaaa
abba
aaaaabaa
babaababb
5
babb
baabaaa
bab
bb
bbabbaab
1
0
3
0
0