211. Add and Search Word - Data structure design
2016-05-26 16:07
281 查看
Design a data structure that supports the following two operations:
search(word) can search a literal word or a regular expression string containing only letters
A
For example:
Note:
You may assume that all words are consist of lowercase letters
题意:设计一种数据结构满足能够快速添加和查询单词。
思路:字典树+递归查询。
void addWord(word) bool search(word)
search(word) can search a literal word or a regular expression string containing only letters
a-zor
..
A
.means it can represent any one letter.
For example:
addWord("bad") addWord("dad") addWord("mad") search("pad") -> false search("bad") -> true search(".ad") -> true search("b..") -> true
Note:
You may assume that all words are consist of lowercase letters
a-z.
题意:设计一种数据结构满足能够快速添加和查询单词。
思路:字典树+递归查询。
class TrieNode{ public: TrieNode* next[26]; bool isword; TrieNode(){ isword = false; memset(next, 0, 26 * sizeof(TrieNode*)); } }; class WordDictionary { public: WordDictionary(){ root = new TrieNode(); } // Adds a word into the data structure. void addWord(string word) { TrieNode* level = root; int index = 0; while (index < word.size()){ int i = word[index] - 'a'; if (level->next[i] == NULL){ level->next[i] = new TrieNode(); } level = level->next[i]; index++; } level->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 search(word, root); } bool search(string word, TrieNode* node){ if (word.empty()){ return node->isword; } TrieNode* level = node; char ch = word[0]; if (ch == '.'){ for (int i = 0; i < 26; i++){ if (level->next[i] != NULL){ if (search(word.substr(1), level->next[i]) == true){ return true; } } } return false; } else{ int i = word[0] - 'a'; if (level->next[i] == NULL){ return false; } else{ return search(word.substr(1), level->next[i]); } } } private: TrieNode* root; }; // Your WordDictionary object will be instantiated and called as such: // WordDictionary wordDictionary; // wordDictionary.addWord("word"); // wordDictionary.search("pattern");
相关文章推荐
- js 使用总结
- UVA 11235Frequent values(RMQ)
- Centos系统备份与恢复教程
- SpringMVC学习之helloworld(一)
- 布隆过滤器(Bloom Filter)详解
- Struts2优点
- 《Android 之美 从0到1 -- 高手之路》
- 不使用广告而采集IDFA的app上架
- sourcetree POST git-receive-pack (chunked)解决方法
- 分布式缓存系统Memcached简介与实践
- 从.snk文件导出密钥
- Matlab中矩阵的平方和矩阵中每个元素的平方介绍
- 寻找小水王
- Intent实现页间面跳转
- k短路 SPFA+A*算法 poj 2449
- The method of type must override asuperclass? annotation:@Override
- KMP_next数组_while详解_Java实现
- CentOS6.5升级内核
- SQL分页的应用
- 【总结】Datax按record限速