//
// main.cpp
// Trie 字典树的实现
//
// Created by zjl on 16/9/24.
// Copyright © 2016年 zjl. All rights reserved.
//
#include <iostream>
#include <string>
#include <vector>
using namespace std;
const int number = 26;
struct TrieNode{
int path;//多少个单词经过这个词
int end;//以此节点为结尾的单词有多少 其实最多就一个
vector<TrieNode*>num;
TrieNode(){
path = 0;
end = 0;
num.reserve(number);
}
};
void inserts(TrieNode* root, string word){
if(word.empty()) return;
TrieNode* p = root;
for(int i = 0; i < word.size(); i++){
int index = word[i] - 'a';
if(p->num[index] == NULL)
p->num[index] = new TrieNode();
p = p->num[index];
p->path++;
}
p->end++;
}
void deletes(TrieNode* root, string word){
if(word.empty()) return;
for(int i = 0; i < word.size(); i++){
int index = word[i] - 'a';
root->num[index]->path --;
if( root->num[index]->path == 0){
root->num[index] = NULL;
return;
}
root = root->num[index];
}
root->end--;
}
bool search(TrieNode* root, string word){
if(word.empty()) return false;
for(int i = 0; i < word.size(); i++){
int index = word[i] - 'a';
if(root->num[index] == NULL)
return false;
root = root->num[index];
}
if(root->end > 0) return true;
else return false;
}
//返回以prefix为前缀的单词的个数
int prefixnumber(TrieNode* root, string word){
if(word.empty()) return 0;
for(int i = 0; i < word.size(); i++){
int index = word[i] - 'a';
if(root->num[index] == NULL){
return 0;
}
root = root->num[index];
}
return root->path;
}
int main(int argc, const char * argv[]) {
// insert code here...
return 0;
}
字典树的增、删、查、找前缀个数
最新推荐文章于 2020-07-21 09:56:11 发布