单词查找树(c++ 版)

来源:互联网 发布:好用的网络电话软件 编辑:程序博客网 时间:2024/06/05 20:27

TireST.h

#pragma once#include <memory>#include <string>class TireST{private:    class Node    {    private:        std::unique_ptr<std::unique_ptr<Node>[]> list;        bool end;    public:        Node(const int& R = 256):list(new std::unique_ptr<Node>[R]), end(false)        {            for (int i = 0; i < R; ++i)                list[i] = nullptr;        }        void put(const std::string& s,const int& pos)        {            if (pos == (s.length() - 1))            {                if (list[s[pos]] == nullptr)                    list[s[pos]] = std::move(std::unique_ptr<Node>(new Node));                list[s[pos]]->end = true;                return;            }            if (list[s[pos]] == nullptr)                list[s[pos]] = std::move(std::unique_ptr<Node>(new Node));            list[s[pos]]->put(s, pos + 1);        }        bool find(const std::string& s, const int& pos)        {               if (pos >= s.length())                return false;            if (pos == (s.length() - 1) && list[s[pos]]->end == true)                return true;            else                return list[s[pos]]->find(s, pos + 1);        }    };private:    std::unique_ptr<Node> root;public:    TireST():root(new Node)    {    }public:    void put(const std::string& s)    {        root->put(s, 0);    }    bool find(const std::string& s)    {        return root->find(s, 0);    }};

main.cpp

#include <iostream>#include "TireST.h"#include <memory>using namespace std;int main(){    TireST ts;    ts.put("Marco");    ts.put("wh");    ts.put("marco");    cout << boolalpha << ts.find("wh");    system("pause");    return 0;}
原创粉丝点击