【leetcode 字典树、前缀树 C++】211. Design Add and Search Words Data Structure

211. Design Add and Search Words Data Structure

在这里插入图片描述

class TrieNode {
    
    
public:
    bool is_end;
    vector<TrieNode*> children = vector<TrieNode*>(26, nullptr);
    TrieNode() {
    
     is_end = false; }
};


class WordDictionary {
    
    
public:
    /** Initialize your data structure here. */
    TrieNode* root = new TrieNode();
    TrieNode* p;
    WordDictionary() {
    
    
    }
    
    void addWord(string word) {
    
    
        int len = word.size();
        p = root;
        for(int ii = 0; ii < len; ii++) {
    
    
            if(!p->children[word[ii] - 'a']) p->children[word[ii] - 'a'] = new TrieNode();
            p = p->children[word[ii] - 'a'];
        }
        p->is_end = true;
    }
    
    bool search(string word) {
    
    
        int word_len = word.size();
        queue<TrieNode*> Q;
        Q.push(root);
        int ii = 0;
        for(; ii < word_len; ii++) {
    
    
            int Q_len = Q.size();
            int num = word[ii] - 'a';
            for(int kk = 0; kk < Q_len; kk++) {
    
    
                p = Q.front();
                Q.pop();
                if(word[ii] != '.') {
    
    
                    if(!p->children[num]) continue;
                    else Q.push(p->children[num]);
                }
                else for(int jj = 0; jj < 26; jj++) if(p->children[jj]) Q.push(p->children[jj]);
            }
        }
        if(ii < word_len) return false;
        while(!Q.empty()) {
    
    
            p = Q.front();
            Q.pop();
            if(p->is_end) return true;
        }
        return false;
    }
};

/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary* obj = new WordDictionary();
 * obj->addWord(word);
 * bool param_2 = obj->search(word);
 */

猜你喜欢

转载自blog.csdn.net/m0_37454852/article/details/113746276
今日推荐