10-19每日一题:Leetcode211. 添加与搜索单词 - 数据结构设计

这篇博客介绍了如何使用字典树数据结构设计一个WordDictionary类,实现添加单词和搜索路径的功能。文章详细阐述了算法思路,包括在添加单词时的O(L)时间复杂度和搜索时的O(26L)时间复杂度。通过深度优先搜索策略,实现了对带通配符的单词搜索。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Leetcode211. 添加与搜索单词 - 数据结构设计

思路:字典树

在字典树的基础上增加一个深度优先遍历,如果遍历到的字符串上字母,直接判断分治是否存在即可,如果是 . . .则需要遍历当前结点的每一个分治

时间复杂度:addword时间复杂度是 O ( L ) O(L) O(L)search时间复杂度是 O ( 2 6 L ) O(26^L) O(26L)
空间复杂度: n n n是单词的个数, L L L是单词的最大长度,复杂度为 O ∗ ( N ∗ L ) O*(N*L) O(NL)
class WordDictionary {
public:
    struct Node
    {
        bool is_end;
        Node *son[26];
        Node()
        {
            is_end = false;
            for (int i = 0; i < 26; i ++ ) son[i] = NULL;
        }
    }*root;

    WordDictionary() {
        root = new Node();
    }
    
    void addWord(string word) {
        auto p = root;
        for (auto c : word) {
            int u = c - 'a';
            if (!p->son[u]) p->son[u] = new Node();
            p = p->son[u];
        }
        p->is_end = true;
    }
    
    bool search(string word) {
        return dfs(root, word, 0);
    }

    bool dfs(Node* p, string& word, int i) {
        if (i == word.size()) return p->is_end;
        if (word[i] != '.') {
            int u = word[i] - 'a';
            if (p->son[u]) return dfs(p->son[u], word, i + 1);
            else return false;
        }
        else {
            for (int j = 0; j < 26; j ++ )
                if (p->son[j] && dfs(p->son[j], word, 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);
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Shirandexiaowo

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

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

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

打赏作者

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

抵扣说明:

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

余额充值