字典树的增、删、查、找前缀个数

来源:互联网 发布:android 仿淘宝首页 编辑:程序博客网 时间:2024/05/21 02:34
////  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;}

0 0