字典树

作者: LxxxR | 来源:发表于2018-08-10 10:35 被阅读0次
    #define MAX_SIZE 26
    class TrieNode {
    public:
        TrieNode *child[MAX_SIZE];
        bool isWord;
        TrieNode() : isWord(false){
            for (int i=0;i<MAX_SIZE;i++)
                child[i]=NULL;
        }
    };
    
    class Trie {
    public:
        Trie() {
            root = new TrieNode();
        }
    
    
        void insert(string s) {
            TrieNode *p = root;
            for (int i=0;i<s.length();i++) {
                int id = s[i] - 'a';
                if (!p->child[id]) 
                    p->child[id] = new TrieNode();
                p = p->child[id];
            }
            p->isWord = true;
        }
    
    
        bool search(string key) {
            TrieNode *p = root;
            for (int i=0;i<key.length();i++) {
                int id = key[i] - 'a';
                if (!p->child[id]) 
                    return false;
                p = p->child[id];
            }
            return p->isWord;
        }
    
        //和search()几乎一样,只是最后返回值不一样
        bool startsWith(string prefix) {
            TrieNode *p = root;
            for (int i=0;i<prefix.length();i++) {
                int id = prefix[i] - 'a';
                if (!p->child[id]) 
                    return false;
                p = p->child[id];
            }
            return true;
        }
    
    private:
        TrieNode* root;
    };
    

    相关文章

      网友评论

          本文标题:字典树

          本文链接:https://www.haomeiwen.com/subject/rqkkbftx.html