关闭

C++字典树

标签: 字典树
468人阅读 评论(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;
}
1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:184677次
    • 积分:4990
    • 等级:
    • 排名:第5640名
    • 原创:291篇
    • 转载:2篇
    • 译文:0篇
    • 评论:96条
    文章分类