实现字典树Trie的基本操作

字典树:根节点不包含字符,除根节点外每一个节点都只包含一个字符; 从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串; 每个节点的所有子节点包含的字符都不相同。

实现字典树的插入insert(),查找search(string key),判断是否有以某字符串为前缀的字符串starsWith(string s)。

实现代码如下,可以将bool hasWord改为一个int型来统计出现的词频。

class TrieNode {
public:
    // Initialize your data structure here.
    TrieNode() {
        hasWord=false;
        for(int i=0; i<26; ++i) {
            child[i]=NULL;
        }
    }
    char data;
    bool hasWord;
    TrieNode *child[26];
};

class Trie {
public:
    Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    void insert(string s) {
        if(s.empty()) {
            return;
        }
        TrieNode *t = root->child[s[0]-'a'], *p=root;
        for(int i=0; i<s.size(); ++i) {
            if( t == NULL) {
                t=new TrieNode();
                t->data=s[i];
                p->child[s[i]-'a']=t;						
            }
            if( i+1 < s.size() ) {
                p=t;
                t=p->child[s[i+1]-'a'];
            }	
        }
        t->hasWord=true;
    }

    // Returns if the word is in the trie.
    bool search(string key) {
        if(key.empty()) {
            return false;
        }
        TrieNode *p=root, *t=p->child[ key[0]-'a' ];
        for(int i=0; i<key.size(); ++i) {
            if(t == NULL) {
                return false;
            }
            if( i+1 < key.size() ) {
                p=t;
                t=p->child[ key[i+1]-'a' ];
            }
        }
        if(t->hasWord == false){
            return false;
        }
        return true;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
        if(prefix.empty()) {
            return false;
        }
        TrieNode *p=root, *t=p->child[ prefix[0]-'a' ];
        for(int i=0; i<prefix.size(); ++i) {
            if(t == NULL) {
                return false;
            }
            if( i+1 < prefix.size() ) {
                p=t;
                t=p->child[ prefix[i+1]-'a' ];
            }
        }
        return true;
    }

private:
    TrieNode* root;
};
    原文作者:Trie树
    原文地址: https://blog.csdn.net/slowdreamer/article/details/45771615
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞