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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值