码迷,mamicode.com
首页 > 编程语言 > 详细

C++字典树

时间:2015-07-09 09:39:45      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:字典树

#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;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

C++字典树

标签:字典树

原文地址:http://blog.csdn.net/liuhuiyan_2014/article/details/46812245

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!