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

208 Implement Trie (Prefix Tree) 字典树(前缀树)

时间:2018-04-08 19:43:48      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:led   ref   new   mem   bsp   ini   obj   next   注意   

实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个方法。
注意:
你可以假设所有的输入都是小写字母 a-z。
详见:https://leetcode.com/problems/implement-trie-prefix-tree/description/

class TrieNode
{
public:
    TrieNode *next[26];
    char c;
    bool isWord;
    TrieNode():isWord(false)
    {
        memset(next,0,sizeof(TrieNode*)*26);
    }
    TrieNode(char _c):c(_c),isWord(false)
    {
        memset(next,0,sizeof(TrieNode*)*26);
    }
};
class Trie {
public:
    /** Initialize your data structure here. */
    Trie() {
        root=new TrieNode();
    }
    
    /** Inserts a word into the trie. */
    void insert(string word) {
        TrieNode *p=root;
        int id;
        for(char c:word)
        {
            id=c-‘a‘;
            if(p->next[id]==nullptr)
            {
                p->next[id]=new TrieNode(c);
            }
            p=p->next[id];
        }
        p->isWord=true;
    }
    
    /** Returns if the word is in the trie. */
    bool search(string word) {
        TrieNode *p=root;
        int id;
        for(char c:word)
        {
            id=c-‘a‘;
            if(p->next[id]==nullptr)
            {
                return false;
            }
            p=p->next[id];
        }
        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;
        int id;
        for(char c:prefix)
        {
            id=c-‘a‘;
            if(p->next[id]==nullptr)
            {
                return false;
            }
            p=p->next[id];
        }
        return true;
    }
private:
    TrieNode *root;
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * bool param_2 = obj.search(word);
 * bool param_3 = obj.startsWith(prefix);
 */

 

208 Implement Trie (Prefix Tree) 字典树(前缀树)

标签:led   ref   new   mem   bsp   ini   obj   next   注意   

原文地址:https://www.cnblogs.com/xidian2014/p/8746752.html

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