Lintcode 单词的添加与查找
来源:互联网 发布:linux 脚本 while 编辑:程序博客网 时间:2024/04/29 08:13
单词的添加与查找
设计一个包含下面两个操作的数据结构:addWord(word)
, search(word)
addWord(word)
会在数据结构中添加一个单词。而search(word)
则支持普通的单词查询或是只包含.
和a-z
的简易正则表达式的查询。
一个 .
可以代表一个任何的字母。
注意事项
你可以假设所有的单词都只包含小写字母 a-z。
样例
addWord("bad")addWord("dad")addWord("mad")search("pad") // return falsesearch("bad") // return truesearch(".ad") // return truesearch("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");
0 0
- Lintcode 单词的添加与查找
- 单词的添加与查找-LintCode
- 单词的存储,查找,替换与删除
- 单词清洗与查找
- 最后一个单词的长度(LintCode)
- LintCode - 422.最后一个单词的长度
- lintcode --最后一个单词的长度
- lintcode:最后一个单词的长度
- lintcode-最后一个单词的长度
- Lintcode最后一个单词的长度
- lintcode 最后一个单词的长度
- 最后一个单词的长度 -LintCode
- Word Search 单词的查找
- 单词查找树的实现
- LintCode 最长单词
- lintcode-单词搜索-123
- lintcode-单词接龙-120
- 最长单词(LintCode)
- 外部接口如何调用EAS凭证接口 实例并合并同一科目的凭证
- Leetcode_338_Counting Bits
- Mac文件大清理 Xcode文件清理
- HCatalog
- [汇编语言学习笔记][第七章更灵活的定位内存的方法]
- Lintcode 单词的添加与查找
- 希尔排序算法
- Retrofit的简单封装--更方便的配置okhttp
- HiveQL:视图
- Java中静态方法和实例方法的区别
- android-Junit单元测试
- HiveQL:索引
- R.NET用于Excel Add-In的多实例(multi-Instance)问题及解决方法(2)
- 远程查询