//
// 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树接口
最新推荐文章于 2021-04-14 23:16:55 发布