zoukankan      html  css  js  c++  java
  • leetcode 211. 添加与搜索单词

    设计一个支持以下两种操作的数据结构:

    void addWord(word)
    bool search(word)
    

    search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 .a-z. 可以表示任何一个字母。

    示例:

    addWord("bad")
    addWord("dad")
    addWord("mad")
    search("pad") -> false
    search("bad") -> true
    search(".ad") -> true
    search("b..") -> true
    

    说明:

    你可以假设所有单词都是由小写字母 a-z 组成的。

    解题思路

    直接用字典树(trie)即可,至于.匹配符直接利用回溯即可。

    #include<bits/stdc++.h>
    
    using namespace std;
    
    
    const int nch = 26;
    const int maxn = 200010;
    
    static auto x = []() {
        std::ios::sync_with_stdio(false);
        std::cin.tie(NULL);
        return 0;
    }
    ();
    
    struct Node {
        int ch[nch];
        bool flag;
    
        void reset() {
            for(int i = 0; i < nch; ++i) {
                ch[i] = -1;
            }
            flag = false;
        }
    };
    
    Node tree[maxn];
    
    class WordDictionary {
    public:
        /** Initialize your data structure here. */
        int tot;
        WordDictionary() {
            tree[tot = 0].reset();
        }
    
        /** Adds a word into the data structure. */
        void addWord(string word) {
            int root = 0;
            for(auto &chr:word) {
                if(tree[root].ch[chr - 'a'] == -1) {
                    tree[root].ch[chr - 'a'] = ++tot;
                    tree[tot].reset();
                }
                root = tree[root].ch[chr - 'a'];
            }
            tree[root].flag = 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 _search(word, 0, 0);
        }
    
        bool _search(string &word, int cur, int root) {
            if(cur == word.size() && tree[root].flag)
                return true;
            if(cur >= word.size() or root == -1)
                return false;
            if(word[cur] == '.') {
                for(int i = 0; i < nch; ++i) {
                    if(tree[root].ch[i] != -1 && _search(word, cur + 1, tree[root].ch[i]))
                        return true;
                }
                return false;
            }
            if(tree[root].ch[word[cur]-'a'] != -1)
                return _search(word, cur + 1, tree[root].ch[word[cur]-'a']);
            return false;
        }
    };
    
    int main() {
    
        return 0;
    }
    
    
  • 相关阅读:
    Shell 同时读取多个文件
    Shell 进度条效果的一个实现
    在 CentOS7 上安装 Tomcat9
    Redis原子计数器incr,防止并发请求
    .Net高并发解决思路
    Redis windows服务器配置可远程连接
    Lambda表达式和For循环使用需要注意的一个地方
    C#多线程和线程池
    MongoDb 物理位置应用实现
    Android Studio3.0 配置AndroidAnnotation注解框架
  • 原文地址:https://www.cnblogs.com/crackpotisback/p/10208107.html
Copyright © 2011-2022 走看看