Leetcode 208. Implement Trie (Prefix Tree) Trie树(前缀树)

208. Implement Trie (Prefix Tree)

Medium

Implement a trie with insert, search, and startsWith methods.

Example:

Trie trie = new Trie();

trie.insert(“apple”);
trie.search(“apple”); // returns true
trie.search(“app”); // returns false
trie.startsWith(“app”); // returns true
trie.insert(“app”);
trie.search(“app”); // returns true
Note:

You may assume that all inputs are consist of lowercase letters a-z.
All inputs are guaranteed to be non-empty strings.

解析:第一次碰到Trie树相关的题目,然后看了下原理,挺简单的,其实就是一颗多叉树,然后每个路径上都有一个字母,
然后如果要插入一个字母的话,那么就在树上查找,如果没找到,那么就新建一个TrieNode节点。最后在叶子节点标识这是一个单词即可,即图中红色部分。时间复杂度为O(n).

看一个图就知道了。

Leetcode 208. Implement Trie (Prefix Tree) Trie树(前缀树)
图来自于 https://blog.****.net/Hackbuteer1/article/details/7964147

代码:

class TrieNode
{
public:
    TrieNode* child[26];  //一个节点可以有26个子节点,即可以分出26个字母
    bool is_word;
    TrieNode():is_word(false)
    {
        for(int i = 0; i < 26; i++)
            child[i] = nullptr;
    }
    ~TrieNode()
    {
        for(int i = 0; i < 26; i++)
            delete child[i];
    }
};

class Trie 
{
private:
    TrieNode* root;
public:
    /** Initialize your data structure here. */
    Trie() 
    {
        root = new TrieNode(); //根节点
    }
    
    /** Inserts a word into the trie. */
    void insert(string word) 
    {
        int len  = word.length();
        TrieNode* p = root;
        for(int i = 0; i < len; i++)
        {
            int index = word[i] - 'a';
            if(!p->child[index])  p->child[index] = new TrieNode();
            p = p->child[index];
        }
        p->is_word = true;
    }


    /** Returns if the word is in the trie. */
    bool search(string word) 
    {
        int len = word.length();
        TrieNode* p = root;
        for(int i = 0; i < len; i++)
        {
            int index = word[i] - 'a';
            if(!p->child[index]) return false;
            p = p->child[index];
        }
        return p->is_word;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) 
    {
        int len = prefix.length();
        TrieNode* p = root;
        for(int i = 0; i < len; i++)
        {
            int index = prefix[i] - 'a';
            if(!p->child[index]) return false;
            p = p->child[index];
        }
        return true;
    }
};

/**
 * 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);
 */