单词查找树(c++ 版)

TireST.h

#pragma once
#include 
#include 

class TireST
{
private:
    class Node
    {
    private:
        std::unique_ptr<std::unique_ptr[]> list;
        bool end;
    public:
        Node(const int& R = 256):list(new std::unique_ptr[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(new Node));
                list[s[pos]]->end = true;
                return;
            }
            if (list[s[pos]] == nullptr)
                list[s[pos]] = std::move(std::unique_ptr(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 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 
#include "TireST.h"
#include 

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

你可能感兴趣的:(算法)