## Trie.h ##
#include<set>
#include<string>
#define BRANCH 26
using namespace std;
struct Node
{
Node * next[BRANCH];
int prefix;
bool isStr;
Node() : prefix(0), isStr(false)
{
memset(next, 0, sizeof(next));
}
};
class Trie
{
private:
Node * root;
set<string> *preSet;
void DFS(Node * ptr, string preStr)
{
for (int i = 0; i < BRANCH; ++i)
{
if (ptr->next[i] != NULL)
{
char chr[] = { 'a' + i, '\0' };
DFS(ptr->next[i], preStr + string(chr));
}
if (ptr->isStr)
{
this->preSet->insert(preStr);
}
}
}
void freeNextArr(Node * ptr)
{
for (int i = 0; i < BRANCH; i++)
{
if (ptr->next[i] != NULL)
{
freeNextArr(ptr->next[i]);
}
}
delete ptr;
}
public:
Trie()
{
root = new Node();
preSet = new set<string>();
}
void insert(const char * word)
{
if (word == NULL)
{
return;
}
Node * ptr = root;
while (*word)
{
if (ptr->next[*word - 'a'] == NULL)
{
ptr->next[*word - 'a'] = new Node();
}
ptr->prefix++;
ptr = ptr->next[*word - 'a'];
++word;
}
ptr->isStr = true;
}
Node* search(const char * word)
{
if (word == NULL)
{
return NULL;
}
Node* ptr = root;
while (ptr&&*word)
{
ptr = ptr->next[*word - 'a'];
++word;
}
return ptr;
}
set<string>* findCommonPrefix_set(const char * prefix)
{
if (prefix == NULL)
{
return NULL;
}
Node* ptr = search(prefix);
if (ptr == NULL)
{
return NULL;
}
DFS(ptr, string(prefix));
return this->preSet;
}
void clearPreSet()
{
this->preSet->clear();
}
void freeMemory()
{
this->freeNextArr(root);
delete this->preSet;
}
};
## 测试程序 ##
#include<iostream>
#include "Trie.h"
void main()
{
Trie comPreTrie;
comPreTrie.insert("abc");
comPreTrie.insert("abcd");
comPreTrie.insert("abcde");
comPreTrie.insert("abcdef");
comPreTrie.insert("abcdefg");
comPreTrie.insert("cde");
Node* ptr = comPreTrie.search("abcd");
if (ptr)
{
printf("num of words prefix by \"abcd\" is %d\n", ptr->isStr ? ptr->prefix + 1 : ptr->prefix);
}
else
{
printf("ptr for \"abcd\" is null");
}
set<string> *comPreSet = comPreTrie.findCommonPrefix_set("abcd");
if (comPreSet)
{
for (set<string>::iterator it = comPreSet->begin(); it != comPreSet->end();++it)
{
printf("%s\n", (*it).c_str());
}
}
else
{
printf("comPreSet for \"abcd\" is null");
}
comPreTrie.clearPreSet();
printf("--------------------------------\n");
ptr = comPreTrie.search("word");
if (ptr)
{
printf("num of words prefix by \"word\" is %d\n",
ptr->isStr ? ptr->prefix + 1 : ptr->prefix);
}
else
{
printf("ptr for \"word\" is null\n");
}
comPreSet = comPreTrie.findCommonPrefix_set("word");
if (comPreSet)
{
for (set<string>::iterator it = comPreSet->begin();
it != comPreSet->end(); ++it)
{
printf("%s\n", (*it).c_str());
}
}
else
{
printf("comPreSet for \"word\" is null\n");
}
comPreTrie.clearPreSet();
comPreTrie.freeMemory();
}
## 运行结果 ##
