码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode@ [208] Implement Trie (Prefix Tree)

时间:2015-11-10 12:15:08      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

Trie 树模板

https://leetcode.com/problems/implement-trie-prefix-tree/

class TrieNode {
public:
    char var;
    bool isWord;
    TrieNode *next[26];
    TrieNode() {
        var = 0;
        this->isWord = false;
        for(auto &c : next) c = NULL;
    }
    TrieNode(char c) {
        var = c;
        this->isWord = false;
        for(auto &c : next) c = NULL;
    }
};

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

    // Inserts a word into the trie.
    void insert(string word) {
        TrieNode *p = root;
        for(auto &a : word) {
            int idx = a - a;
            if(!p->next[idx]) p->next[idx] = new TrieNode();
            p = p->next[idx];
        }
        p->isWord = true;
    }

    // Returns if the word is in the trie.
    bool search(string word) {
        TrieNode *p = root;
        for(auto &a : word) {
            int idx = a - a;
            if(!p->next[idx]) return false;
            p = p->next[idx];
        }
        return p->isWord;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
        TrieNode *p = root;
        for(auto &a : prefix) {
            int idx = a - a;
            if(!p->next[idx]) return false;
            p = p->next[idx];
        }
        return true;        
    }

private:
    TrieNode* root;
};

// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");

 

leetcode@ [208] Implement Trie (Prefix Tree)

标签:

原文地址:http://www.cnblogs.com/fu11211129/p/4952245.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!