LeetCode每日一题 DAY3:LeetCode 211. 添加与搜索单词 - 数据结构设计

 解题思路:tire树+dfs搜索

存储的单词都是小写字母,所以用tire树来存。

对于查询的单词来说:

如果遇到'.',则枚举所有的存在的下一个字母进行搜索。
否则是单词,搜索下一个字母节点即可。

 插入每个字符串:时间复杂度O(N)

查询每个字符串:最坏遍历所有的节点,时间复杂度O(NM)

空间复杂度O(26N)

class WordDictionary {
public:
    WordDictionary* next[26];
    bool isEnd;

    WordDictionary() {
        isEnd = false;
        memset(next, 0, sizeof(next));
    }
    
    void addWord(string word) {
        WordDictionary* node = this;

        for (char c : word){
            int u = c - 'a';
            if (node -> next[u] == NULL) node -> next[u] = new WordDictionary();
            node = node -> next[u];
        }
        
        node -> isEnd = true;
    }

    bool dfs(string& word, int k, WordDictionary* node){
        if (k == word.size()) return node -> isEnd; //字符串枚举到最后了
        //字符不为.
        if (word[k] != '.'){
            int u = word[k] - 'a';
            if (node -> next[u] != NULL) return dfs(word, k + 1, node -> next[u]);
            return false;
        }
        //为.,需要枚举所有的存在的下一个字母进行搜索
        for (int i = 0; i < 26; i ++){
            if (node -> next[i] && dfs(word, k + 1, node -> next[i])) 
            return true;
        }
        return false;
    }
    
    bool search(string word) {
        WordDictionary* root = this;
        return dfs(word, 0, root);
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Roadrunnner

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值