字典树的c++实现

//字典树
//2016.6.6
//yqtao@whu.edu.cn
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
const int Num = 26;//
struct TrieNode
{
    bool Isword;//判断是否是单词
    TrieNode* next[Num];
    TrieNode() :Isword(false)//初始化
    {
        memset(next, NULL, sizeof(next));
    }
};
class Trie
{
public:
    Trie() { root = new TrieNode(); }
    void insert(string word);
    bool search(string word);
    void deleteTrie(TrieNode* root);
private:
    TrieNode* root;
};
void Trie::insert(string word)
{
    TrieNode* location = root;
    for (int i = 0; i < word.length();i++)
    {
        if (location->next[word[i] - 'a'] == nullptr)
        {
            TrieNode* temp = new TrieNode();
            location->next[word[i] - 'a']=temp;
        }
        location = location->next[word[i] - 'a'];
    }
    location->Isword = true;
}
bool Trie::search(string word)
{
    TrieNode* location = root;
    //while (word&&location)//注意location不能为空
    for (int i = 0; i < word.length()&&location;i++)
        location = location->next[word[i] - 'a'];
    return(location != NULL && location->Isword);
}
void Trie::deleteTrie(TrieNode* root)
{
    for (int i = 0; i < Num; i++)
    {
        if (root->next[i] != NULL)
        {
            deleteTrie(root->next[i]);
        }
    }
    delete root;
}
void main() //简单测试  
{
    Trie tree;
    int n;//输入n个单词在字典树中
    cin >> n;
    while (n--)
    {
        string s;
        cin >> s;
        tree.insert(s);
    }
    string input;
    cout << "输入要检查的单词" << endl;
    cin >> input;
    cout << boolalpha << tree.search(input) << endl;//查找是否存在是个单词
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值