欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Add and Search Word - Data structure design

程序员文章站 2022-03-10 08:18:06
...

Add and Search Word - Data structure design

1. 解析

题目大意,建立对应的字典树结构,查找所给的单词是否存在字典树当中,'.' 可以匹配26个字母当中的任何一个。

2. 分析

本题的难点在于'.'的处理,它可以任意匹配26个字母当中的任何一个,很明显利用深度优先检索是最合适的,当匹配到'.'时,对当前指针任意取一个非空指针,代表当前位置上的字母已经出现,继续往下搜索,若不能满足条件,再回溯到当前指针,继续搜索下一个非空指针,...直到检索到最后的状态

struct dictTree{
    dictTree* dict_tree[26];
    int val;
    bool isWord;
    dictTree() : isWord(false){
        for (int i = 0; i < 26; ++i) dict_tree[i] = NULL;
    }
};
class WordDictionary {
public:
    /** Initialize your data structure here. */
    WordDictionary() {
        this->root = new dictTree();
    }
    
    /** Adds a word into the data structure. */
    void addWord(string word) {
        dictTree* cur = root;
        for (int i = 0; i < word.length(); ++i){
            int index = word[i] - 'a';
            if (! cur->dict_tree[index]) //为空
                cur->dict_tree[index] = new dictTree();
            cur = cur->dict_tree[index];
        }
        cur->isWord = true;
    }
    
    /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
    bool search(string word){
        return searchDFS(word, root, 0);
    }
    bool searchDFS(string& word, dictTree* cur, int pos){
        if (pos == word.size()) return cur->isWord;
        if (word[pos] == '.'){
            for (auto nextCur : cur->dict_tree){
                if (nextCur && searchDFS(word, nextCur, pos + 1)) return true;
            }
            return false;
        }
        else{
            int index = word[pos] - 'a';
            return cur->dict_tree[index] && searchDFS(word, cur->dict_tree[index], pos + 1);
        }
    }
private:
    dictTree* root;
};

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

3. 类似题目

 Implement Trie (Prefix Tree)

Word Ladder

[1]https://www.cnblogs.com/grandyang/p/4507286.html