博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Add and Search Word - Data structure design 添加和查找单词-数据结构设计
阅读量:6899 次
发布时间:2019-06-27

本文共 2162 字,大约阅读时间需要 7 分钟。

Design a data structure that supports the following two operations:

void addWord(word)bool search(word)

search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

For example:

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

Note:

You may assume that all words are consist of lowercase letters a-z.

You should be familiar with how a Trie works. If not, please work on this problem:   first.

LeetCode出新题的速度越来越快了,有点跟不上节奏的感觉了。这道题如果做过之前的那道的话就没有太大的难度了,还是要用到字典树的结构,唯一不同的地方就是search的函数需要重新写一下,因为这道题里面'.'可以代替任意字符,所以一旦有了'.',就需要查找所有的子树,只要有一个返回true,整个search函数就返回true,典型的DFS的问题,其他部分跟上一道实现字典树没有太大区别,代码如下:

class WordDictionary {public:    struct TrieNode {    public:        TrieNode *child[26];        bool isWord;        TrieNode() : isWord(false) {            for (auto &a : child) a = NULL;        }    };        WordDictionary() {        root = new TrieNode();    }        // Adds a word into the data structure.    void addWord(string word) {        TrieNode *p = root;        for (auto &a : word) {            int i = a - 'a';            if (!p->child[i]) p->child[i] = new TrieNode();            p = p->child[i];        }        p->isWord = 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 searchWord(word, root, 0);    }        bool searchWord(string &word, TrieNode *p, int i) {        if (i == word.size()) return p->isWord;        if (word[i] == '.') {            for (auto &a : p->child) {                if (a && searchWord(word, a, i + 1)) return true;            }            return false;        } else {            return p->child[word[i] - 'a'] && searchWord(word, p->child[word[i] - 'a'], i + 1);        }    }    private:    TrieNode *root;};// Your WordDictionary object will be instantiated and called as such:// WordDictionary wordDictionary;// wordDictionary.addWord("word");// wordDictionary.search("pattern");

本文转自博客园Grandyang的博客,原文链接:,如需转载请自行联系原博主。

你可能感兴趣的文章
EMOS1.5更新
查看>>
mantis上传文件设置与存放路径
查看>>
Lync for iphone
查看>>
SQL SERVER数据库权限
查看>>
Linux 中 10 个有用的命令行补全例子
查看>>
【思想篇之爱左看右】
查看>>
Hadoop2.6+Zookeeper3.4+Hbase1.0部署安装
查看>>
测试唯一ID支持多大的并发量
查看>>
老鸟经验谈linux运维人员到底要不要考linux认证
查看>>
solr配置
查看>>
CSS HACK 区别于ie6/7/8/firefox的小问题
查看>>
编译一个可以用Qemu进行Debug的Linux Kernel:
查看>>
linux 服务器 keras 深度学习环境搭建
查看>>
xshell+xmanager远程linux图形化界面
查看>>
布局模型
查看>>
我的友情链接
查看>>
jquery 实现复选框 全选/反选
查看>>
我的友情链接
查看>>
http://www.mossle.com/wiki/13.lemon-devguide/0008.modeler
查看>>
UI自动化测试之selenium(3)——采坑填坑集
查看>>