博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
字典树的c++实现
阅读量:4185 次
发布时间:2019-05-26

本文共 1537 字,大约阅读时间需要 5 分钟。

//字典树//2016.6.6//yqtao@whu.edu.cn#include "stdafx.h"#include 
#include
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;//查找是否存在是个单词}

转载地址:http://qidoi.baihongyu.com/

你可能感兴趣的文章
Git拉取远程仓库
查看>>
退出MySQL
查看>>
查看pip版本
查看>>
更新pip版本至最新
查看>>
Python str.ljust方法:字符串左对齐排版
查看>>
Linux下安装pyenv
查看>>
virsh查询虚拟机列表
查看>>
右上三角矩阵的压缩(Python实现)
查看>>
Linux man 命令:查询命令使用手册
查看>>
CentOS配置静态ip
查看>>
Jinja2条件控制
查看>>
Linux /usr/src/kernels 缺失内核源码解决方案
查看>>
Git分支管理
查看>>
查看MySQL支持的字符集
查看>>
常见Linux目录
查看>>
在CLI中打印表格----gotable使用介绍
查看>>
Python str rjust方法
查看>>
CentOS7 安装MySQL
查看>>
Linux cd 命令 ----切换目录
查看>>
MySQL校对集
查看>>