Leetcode 211. 添加与搜索单词 - 数据结构设计 解题思路及C++实现

解题思路:

用字典树来作为存储的数据结构。

新增单词的时候,就使用字典树插入新单词的方法,与LeetCode 208 题一样。

在查找某一个字典树时,使用深度优先搜索即可。

 

class WordDictionary {
public:
    //定义字典树中每个节点的结构
    struct Node{
        bool isword = false;  //用于标记当前节点是否为单词的最后一个字符
        Node* next[27] = {};
    };
    Node* root;  //每一个class都有一棵字典树
    /** Initialize your data structure here. */
    WordDictionary() {
        root = new Node(); //新建一棵字典树
    }
    
    /** Adds a word into the data structure. */
    void addWord(string word) {
        Node* tmp = root;
        for(auto w: word){
            if(tmp->next[w - 'a'] == NULL){ //还没有这个节点
                Node* tt = new Node();
                tmp->next[w - 'a'] = tt;   //那就新建节点
            }
            tmp = tmp->next[w - 'a'];
        }
        tmp->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 dfs(word, root, 0);
    }
    
    bool dfs(string word, Node* root, int i){
        if(!root) return false;
        if(i >= word.size()) return root->isword; //看看是不是一个完整的单词
        if(word[i] != '.'){
            if(root->next[word[i] - 'a']){
                return dfs(word, root->next[word[i] - 'a'], i+1);
            }
            else return false;
        }
        for(auto t: root->next){
            if(t){
                if(dfs(word, t, i+1)) 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);
 */

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值