tires树接口

//
//  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 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值