[LintCode] Add and Search Word 添加和查找单词
2016-06-11 01:19
591 查看
Design a data structure that supports the following two operations: addWord(word) and 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.
Notice
You may assume that all words are consist of lowercase letters a-z.
Example
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") // return false
search("bad") // return true
search(".ad") // return true
search("b..") // return true
LeetCode上的原题,请参见我之前的博客Add and Search Word - Data structure design。
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.
Notice
You may assume that all words are consist of lowercase letters a-z.
Example
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") // return false
search("bad") // return true
search(".ad") // return true
search("b..") // return true
LeetCode上的原题,请参见我之前的博客Add and Search Word - Data structure design。
class WordDictionary { public: struct TrieNode { bool isLeaf; TrieNode *child[26]; }; WordDictionary() { root = new TrieNode(); } // Adds a word into the data structure. void addWord(string word) { TrieNode *p = root; for (char c : word) { int i = c - 'a'; if (!p->child[i]) p->child[i] = new TrieNode(); p = p->child[i]; } p->isLeaf = 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) { search(word, root, 0); } bool search(string &word, TrieNode *p, int i) { if (i == word.size()) return p->isLeaf; if (word[i] == '.') { for (auto a : p->child) { if (a && search(word, a, i + 1)) return true; } return false; } else { return p->child[word[i] - 'a'] && search(word, p->child[word[i] - 'a'], i + 1); } } private: TrieNode *root; };
相关文章推荐
- 【总结】排序算法汇总
- 大事记
- Mysql+IIS+三层架构创建网站遇到的过程总结
- 你的数据安全吗
- MySQL绿色版(zip解压版)的安装图文教程(mysql-5.6.22-win32.zip)
- Debian8.5安装编译GCC6.1.0笔记
- Java基础-包讲解
- SICP 习题2.10 区间除法 被除区间横跨0的问题
- 短信备份与还原&AsyncTask&程序锁(Fragment)
- Android手机平板两不误,使用Fragment实现兼容手机和平板的程序
- UIResponder介绍
- Android View工作机制(2)—measure过程 上
- 移动端用户体验:获取用户权限的正确方式
- 梳理mybatis-使用篇
- C++作业7
- 将单链表中相邻两节点对换
- 通过改变纹理的UV坐标实现简单的水流效果
- (七)Linux基础之文件的属性及权限
- hihi
- 最近学习的内容