字典樹基礎功能實現 力扣208.實現Trie

詳細題解鏈接戳這
在這裏插入圖片描述

class Trie {
public:
    bool isend;
    Trie* next[26];
    /** Initialize your data structure here. */
    Trie() {
        isend = false;
        memset(next,0,sizeof(next));
    }
    
    /** Inserts a word into the trie. */
    void insert(string word) {
        Trie* node = this;
        for(char c : word){
            if(node->next[c - 'a'] == NULL){
                node->next[c - 'a'] = new Trie;
            }
            node = node->next[c - 'a'];
        }
        node->isend = true;
    }
    
    /** Returns if the word is in the trie. */
    bool search(string word) {
        Trie* node = this;
        for(char c : word){
            node = node->next[c - 'a'];
            if(node == NULL){
                return false;
            }
        }
        return node->isend;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        Trie* node = this;
        for(char c : prefix){
            node = node->next[c - 'a'];
            if(node == NULL){
                return false;
            }
        }
        return true;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章