标签:字典树
#include <iostream>
#include <vector>
#define _MAX_ 256
using namespace std;
struct Node
{
Node *next[_MAX_];
int count[_MAX_];//计数,看这个字符出现的次数。
Node()
{
int i=0;
for (; i < _MAX_; i++)
{
count[i] = 0;
}
for (i = 0; i < _MAX_; i++)
{
next[i] = NULL;
}
}
};
class Trie
{
public:
Trie(vector<string> &vt)
{
root = NULL;
if (root == NULL)
{
root = new Node();
}
Node *p = root;
Node *pr = NULL;
int len;
vector<string> ::iterator it = vt.begin();
while (it != vt.end())
{
len = it->size();
p = root;
for (int i = 0; i < len; i++)
{
if (p == NULL)
{
p = new Node();
pr->next[(*(it))[i-1]] = p;
}
if(p->count[(*it)[i]] == 0)
{
p->count[(*it)[i]]++;
pr = p;
//cout << (*it)[i] << endl;
p = p->next[(*it)[i]];
}
else
{
pr = p;
p = p->next[(*it)[i]];
}
}
it++;
}
}
bool Find(char *s)
{
Node *p = root;
while (*s != ‘\0‘)
{
if (p->count[*s] != 0)
{
//cout << ((char)*s) << " ";
p = p->next[*s];
}
else
{
if (*s != ‘\0‘)
return false;
}
s++;
}
return true;
}
private:
Node *root;
};
int main()
{
vector<string> s;
s.push_back("abc");
s.push_back("bcdef");
s.push_back("12abcew");
s.push_back("abdsac");
s.push_back("fsabc");
s.push_back("413abc");
s.push_back("liuhuiyan");
Trie t(s);
cout << t.Find("liuhuiyan") << endl;;
cout << t.Find("123") << endl;
cout << t.Find("bcdef") << endl;
cout << t.Find("abc")<<endl;
cout << t.Find("12345")<<endl;
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:字典树
原文地址:http://blog.csdn.net/liuhuiyan_2014/article/details/46812245