网站首页 文章专栏 数据结构-前缀树
数据结构-前缀树
创建于:2020-08-15 16:00:00 更新于:2024-04-26 21:08:29 羽瀚尘 727
数据结构 数据结构

Leetcode 208

class Trie {
    Trie *child[26];
    bool is_word;
public:
    /** Initialize your data structure here. */
    Trie() {
        is_word = false;
        for(int i = 0; i < 26; i++) child[i] = NULL;
    }

    /** Inserts a word into the trie. */
    void insert(string word) {
        // find a position to insert
        Trie *t = this;
        for(int i = 0; i < word.size(); i++){
            char c = word[i];
            if(!t->child[c - 'a']) t->child[c - 'a'] = new Trie();
            t = t->child[c - 'a'];
        }
        t->is_word = true;
    }

    /** Returns if the word is in the trie. */
    bool search(string word) {
        Trie *t = this;
        for(int i = 0; i < word.size(); i++){
            char c = word[i];
            if(!t->child[c - 'a']){
                return false;
            } 
            t = t->child[c - 'a'];
        }
        return t->is_word;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        Trie *t = this;
        for(int i = 0; i < prefix.size(); i++){
            char c = prefix[i];
            if(!t->child[c - 'a']){
                return false;
            } 
            t = t->child[c - 'a'];
        }
        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);
 */

待补充:前缀树的应用场景,相关的算法题目。