2021.10.19打卡

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

思路:前缀树

添加单词,将单词添加到字典树

搜索单词,从字典树的根节点开始搜索,遇到点号,对于所有的子节点进行遍历;如果是字母,判断对应的子节点是否存在

struct TrieNode{
    vector<TrieNode*> child;
    bool isEnd;
    TrieNode(){
        child = vector<TrieNode*>(26, nullptr);
        isEnd = false;
    }
};

void insert(TrieNode* root, const string& word){
    TrieNode* node = root;
    for(const char& c:word){
        if(node->child[c-'a']==nullptr){
            node->child[c-'a']=new TrieNode();
        }
        node=node->child[c-'a'];
    }
    node->isEnd=true;
}

class WordDictionary {
public:
    WordDictionary() {
        root=new TrieNode();
    }
    
    void addWord(string word) {
        insert(root,word);
    }
    
    bool search(string word) {
        return dfs(root,0,word);
    }

    bool dfs(TrieNode* root, int index, string& word){
        if(root==nullptr) return false;
        if(index==word.size()){
            return root->isEnd;
        }
        char ch=word[index];
        if(ch>='a'&&ch<='z'){
            TrieNode* child=root->child[ch-'a'];
            return dfs(child,index+1,word);
        }
        else{
            for(TrieNode* child:root->child){
                if(dfs(child,index+1,word))
                    return true;
            }
        }
        return false;   
    }

    TrieNode* root;
};

时间复杂度 初始化 O(1) 添加单词 O(|S|) S是单词长度 搜索单词 O(|∑|S) ∑是字符集,这道题|∑|=26

空间复杂度 O(|∑|*|T|) |T|是所有添加单词的长度之和

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值