//
// Tries.h
// tries
//
// Created by zihe on 16/8/24.
// Copyright © 2016年 zihe. All rights reserved.
//
#ifndef Tries_h
#define Tries_h
#include <string>
using namespace std;
class TrieNode {
public:
TrieNode() {
for(int i = 0; i < 26; i++)
{
next[i] = NULL;
count[i] = 0;
}
isString = false;
}
TrieNode *next[26];
bool isString;
int count[26]; //统计经过该字符的词数
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
// 插入字符串
void insert(string word) {
TrieNode *p = root;
for(int i = 0; i < word.size(); i++){
if(p->next[word[i]-'a'] == NULL){
p->next[word[i]-'a'] = new TrieNode();
p->count[word[i]-'a'] += 1;
}
p = p->next[word[i]-'a'];
}
p->isString = true;
}
// Returns if the word is in the trie.
bool search(string word) {
TrieNode *p = root;
for(int i = 0; i < word.size(); i++){
if(p == NULL) return false;
p = p->next[word[i]-'a'];
}
if(p == NULL || p->isString == false) return false;
return true;
}
void delet(string word)
{
if(!search(word))
{
cout<<"不存在该词"<<endl;
}
TrieNode *p = root;
for(int i=0; i < word.size(); ++i)
{
if(p->count[word[i]-'a']>1) p->count[word[i]-'a']--;
else
{
p->count[word[i]-'a'] = 0;
p->next[word[i]-'a'] = NULL;
}
}
p->isString = false;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
TrieNode *p = root;
for(int i = 0; i < prefix.size(); i++) {
p = p->next[prefix[i]-'a'];
if(p == NULL) return false;
}
return true;
}
private:
TrieNode* root;
};
#endif /* Tries_h */
tires树接口
最新推荐文章于 2022-11-27 17:16:53 发布
本文介绍了一种Trie树(字典树)的数据结构实现方法,并提供了详细的C++代码示例。通过本文,读者可以了解到如何使用Trie树进行字符串的插入、搜索及删除操作。
3万+

被折叠的 条评论
为什么被折叠?



