Lintcode 单词的添加与查找
2016-04-20 18:07
537 查看
单词的添加与查找
描述笔记
数据
评测
设计一个包含下面两个操作的数据结构:
addWord(word),
search(word)
addWord(word)会在数据结构中添加一个单词。而
search(word)则支持普通的单词查询或是只包含
.和
a-z的简易正则表达式的查询。
一个
.可以代表一个任何的字母。
您在真实的面试中是否遇到过这个题?
Yes
注意事项
你可以假设所有的单词都只包含小写字母 a-z。
样例
addWord("bad") addWord("dad") addWord("mad") search("pad") // return false search("bad") // return true search(".ad") // return true search("b..") // return true
AC代码如下:
struct trieNode { trieNode() : terminableSize(0) { for (int i = 0; i < 26; ++i) { children[i] = NULL; } } ~trieNode() { for (int i = 0; i < 26; ++i) { if (children[i]) { delete children[i]; children[i] = NULL; } } } int terminableSize; trieNode *children[26]; }; class WordDictionary { public: WordDictionary() : root(new trieNode) {} size_t Index(char c) { return static_cast<size_t>(c % 26); } // Adds a word into the data structure. void addWord(string word) { // Write your code here trieNode *cur = root; for (size_t i = 0; i < word.size(); ++i) { size_t idx = Index(word[i]); if (!cur->children[idx]) { cur->children[idx] = new trieNode; } cur = cur->children[idx]; } ++cur->terminableSize; } // 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_dfs(word, root); } bool search_dfs(string word, trieNode *cur) { if (word.size() == 0 && cur->terminableSize > 0) return true; for (size_t i = 0; i < word.size(); ++i) { if (word[i] == '.') { for (size_t j = 0; j < 26; ++j) { if (cur->children[j] && search_dfs(word.substr(i + 1), cur->children[j])) return true; } return false; } else { size_t idx = Index(word[i]); if (!cur->children[idx]) return false; cur = cur->children[idx]; } } if (cur->terminableSize > 0) return true; return false; } private: trieNode *root; }; // Your WordDictionary object will be instantiated and called as such: // WordDictionary wordDictionary; // wordDictionary.addWord("word"); // wordDictionary.search("pattern");
相关文章推荐
- caffe windows 编译成功,但是运行时遇到GPU错误
- R.NET用于Excel Add-In的多实例(multi-Instance)问题及解决方法(2)
- android-Junit单元测试
- Java中静态方法和实例方法的区别
- Hadoop Common源码分析之SerializationFactory、Serialization
- 希尔排序算法
- Mac下安装Opencv并配置Xcode
- HiveQL:视图
- HiveQL:索引
- [置顶] [汇编语言学习笔记][第七章更灵活的定位内存的方法]
- Leetcode_338_Counting Bits
- [汇编语言学习笔记][第七章更灵活的定位内存的方法]
- urllib2模块 异常处理
- LeetCode 313 Super Ugly Number
- Android Selector 与 Shape 基本用法
- HCatalog
- iOS-金额小写转大写
- Eclipse开发web项目中关于HttpServletRequest包的问题
- 害人的VS2008,manifest导致“应用程序配置不正确,应用程序未能启动” [转载]
- asp SqlDataSource模糊查询的问题