[leetcode]211. 添加与搜索单词(Trie+DFS)

题目链接

题意

实现词典类 WordDictionary

  • WordDictionary() 初始化词典对象
  • void addWord(word)word 添加到数据结构中,之后可以对它进行匹配
  • bool search(word) 如果数据结构中存在字符串与 word 匹配,则返回 true ;否则,返回 falseword 中可能包含一些 '.' ,每个 . 都可以表示任何一个字母

思路

.通配符 ,所以处理的时候要dfs处理遇到通配符的情况 枚举每条能走的路

题目给出的框架:

class WordDictionary {
public:
    WordDictionary() {
        
    }
    
    void addWord(string word) {
        
    }
    
    bool search(string word) {
        
    }
};

/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary* obj = new WordDictionary();
 * obj->addWord(word);
 * bool param_2 = obj->search(word);
 */
 

Code

class WordDictionary {
private:
    const int N = 2e5+10;
    vector<vector<int>>son;
    vector<int>cnt;
    int idx=0;
public:
    WordDictionary() : son(N,vector<int>(26)),cnt(N) {}
    
    void addWord(string word) {
        int p=0;
        for(char c:word){
            int u=c-'a';
            if(son[p][u]==0) son[p][u]=++idx;
            p=son[p][u];
        }
        cnt[p]++;
    }
    
    bool search(string word) {
        int n=word.size();

        function<bool(int,int)>dfs=[&](int p,int i)->bool{
            if(i==n) return cnt[p]>0;
            if(word[i]=='.'){
                for(int j=0;j<26;j++){
                    if(son[p][j]!=0){
                        bool flag=dfs(son[p][j],i+1);
                        if(flag) return 1;
                    }
                }
                return 0;
            }else{
                char c=word[i];
                int u=c-'a';
                if(son[p][u]!=0){
                    bool flag=dfs(son[p][u],i+1);
                    if(flag) return 1;
                }
                return 0;
            }
            return 0;
        };
        return dfs(0,0);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值