ITPub博客

首页 > > > [LeetCode] Implement Trie (Prefix Tree)

[LeetCode] Implement Trie (Prefix Tree)

作者:Ruiyuan Li 时间:2015-05-11 00:00:00 0 删除 编辑

Implement Trie (Prefix Tree)


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

Note:
You may assume that all inputs are consist of lowercase letters a-z.

解题思路:

前缀树。由于值设定为在a-z之间,我们可以假设是一棵26叉树。注意,每个节点还需要加入一个标记,表明从根到这个节点的路径组成的序列是否为单词。

class TrieNode {
public:
    // Initialize your data structure here.
    TrieNode() {
        this->bWord=false;
        for(int i=0; i<26; i++){
            this->son[i] = NULL;
        }
    }
    
    TrieNode* getSon(char c){
        return this->son[c-'a'];
    }
    
    void setSon(int i, TrieNode* node){
        this->son[i] = node;
    }
    
    bool isWord(){
        return this->bWord;
    }
    
    void markAsWord(){
        this->bWord = true;
    }
private:
    bool bWord;
    TrieNode* son[26];
};

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

    // Inserts a word into the trie.
    void insert(string s) {
        int len = s.length();
        TrieNode* parent = root, *node;
        for(int i=0;igetSon(s[i]);
            if(node == NULL){
                node=new TrieNode();
                parent->setSon(s[i] - 'a', node);
            }
            parent = node;
        }
        parent->markAsWord();
    }

    // Returns if the word is in the trie.
    bool search(string key) {
        int len = key.length();
        TrieNode* node = root;
        for(int i=0; igetSon(key[i]);
            if(node==NULL){
                return false;
            }
        }
        return node->isWord();
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
        int len = prefix.length();
        TrieNode* node = root;
        for(int i=0; igetSon(prefix[i]);
            if(node==NULL){
                return false;
            }
        }
        return true;
    }

private:
    TrieNode* root;
};

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


<!-- -->

原文作者:;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2020-05-21

  • 博文量
    495
  • 访问量
    4827