leetcode208

Posted AsenYang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode208相关的知识,希望对你有一定的参考价值。

class TrieNode {
public:
    // Initialize your data structure here.
    TrieNode() {
            words=0;
            prefixs=0;
            for(int i=0;i<26;i++)
               edges[i]=NULL; 
        }
        int words;
        int prefixs;
        TrieNode* edges[26];
};

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

    // Inserts a word into the trie.
    void insert(string word) {
            insertHelper(root,word,0);
    }

    // Returns if the word is in the trie.
    bool search(string word) {
            return searchHelper(root,word,0)!=0;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
            return startsWithHelper(root,prefix,0)!=0;
    }

    void insertHelper(TrieNode * node,string &word,int pos) {
        if(pos==word.size())
        {
            node->words++;
            node->prefixs++;
        }
        else
        {
            node->prefixs++;
            int char_code=word[pos]-a;
            if(node->edges[char_code]==NULL)
                node->edges[char_code]=new TrieNode();
            insertHelper(node->edges[char_code],word,pos+1);
        }
    }

    int searchHelper(TrieNode * node,string &word,int pos)
    {
        int char_code=word[pos]-a;
        if(pos==word.size())
            return node->words;
        else if(node->edges[char_code]==NULL)
            return 0;
        else 
            return searchHelper(node->edges[char_code],word,pos+1);
    }

    int startsWithHelper(TrieNode * node,string &word,int pos)
    {
        int char_code=word[pos]-a;
        if(pos==word.size())
            return node->prefixs;
        else if(node->edges[char_code]==NULL)
            return 0;
        else
            return startsWithHelper(node->edges[char_code],word,pos+1);
    }

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

 

以上是关于leetcode208的主要内容,如果未能解决你的问题,请参考以下文章

[JavaScript 刷题] 树 - 实现前缀树, leetcode 208

LeetCode 208.实现Trie(字典树) - JavaScript

leetcode208

leetcode-208-实现前缀树

[LeetCode] 208. 实现 Trie (前缀树)

LeetCode 208. 实现 Trie (前缀树)