C++字典树

#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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值