#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
#define N 26
struct TrieNode {
char *data;
TrieNode* branch[N];
TrieNode() {
data = NULL;
for (int i = 0; i < N; i++) branch[i] = NULL;
}
};
class Trie {
public:
TrieNode *root;
Trie() { root = NULL; }
/**
* insert into the tree, with the key: word, the value: entry
*/
void insert(char *word, char *entry) {
if (root == NULL) root = new TrieNode();
TrieNode *location = root;
int level = 0;
while (location!=NULL && level<strlen(word)) {
int branch_code = 0;
if (word[level]<='z' && word[level]>='a') branch_code = word[level]-'a';
else if (word[level]<='Z' && word[level]>='A') branch_code = word[level]-'A';
else return; // error input, just ignore
if (location->branch[branch_code]==NULL) location->branch[branch_code] = new TrieNode();
location = location->branch[branch_code];
level++;
}
if (location->data==NULL) {
location->data = new char[strlen(entry)];
strcpy(location->data, entry);
}
}
/**
* search in the tree and find the value corresponding to the key: word,
* The value will be copied into entry
*/
bool search(char *word, char *entry) {
TrieNode* location = root;
int level = 0;
while (location!=NULL && level<strlen(word)) {
int branch_code = 0;
if (word[level]<='z' && word[level]>='a') branch_code = word[level]-'a';
else if (word[level]<='Z' && word[level]>='A') branch_code = word[level]-'A';
else return false;
location = location->branch[branch_code];
level++;
}
if (location!=NULL && location->data!=NULL) {
strcpy(entry, location->data);
return true;
}
return false;
}
};
int main() {
Trie t;
char entry[100];
t.insert("a", "DET");
t.insert("abacus","NOUN");
t.insert("abalone","NOUN");
t.insert("abandon","VERB");
t.insert("abandoned","ADJ");
t.insert("abashed","ADJ");
t.insert("abate","VERB");
t.insert("this", "PRON");
t.insert("this", "PRON_Ignored"); // this will be ignored
if (t.search("this", entry))
cout<<"'this' was found. pos: "<<entry<<endl;
if (t.search("abate", entry))
cout<<"'abate' is found. pos: "<<entry<<endl;
if (t.search("baby", entry))
cout<<"'baby' is found. pos: "<<entry<<endl;
else
cout<<"'baby' does not exist at all!"<<endl;
return 0;
}
输出:
'this' was found. pos: PRON
'abate' is found. pos: VERB
'baby' does not exist at all!