Add and Search Word - Data Structure Design
2015-08-18 23:02
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
For example:
Note:
You may assume that all words are consist of lowercase letters
Analyse: The same as Implement Trie. If '.' is encountered, we need to traversal all situations.
Runtime: 88ms.
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.
Analyse: The same as Implement Trie. If '.' is encountered, we need to traversal all situations.
Runtime: 88ms.
class TrieNode{ public: TrieNode* childNode[27]; bool isVal; TrieNode(){ isVal = false; for(int i = 0; i < 27; i++) childNode[i] = NULL; } }; class WordDictionary { private: TrieNode* root; public: WordDictionary(){ root = new TrieNode(); } // Adds a word into the data structure. void addWord(string word) { TrieNode* temp = root; for(int i = 0; i < word.size(); i++){ int index = word[i] - 'a'; if(word[i] == '.') index = 26; else{ if(temp->childNode[index] == NULL) temp->childNode[index] = new TrieNode(); } temp = temp->childNode[index]; } temp->isVal = true; //word has been inserted } // 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 levelSearch(word, root, 0); } bool levelSearch(string& word, TrieNode* root, int index){ TrieNode* temp = root; if(!temp) return false; //length of the word is larger than that of the strings in the trie if(index >= word.size()) return temp->isVal; if(word[index] != '.') return levelSearch(word, temp->childNode[word[index] - 'a'], index + 1); else{ for(int i = 0; i < 26; i++) if(levelSearch(word, temp->childNode[i], index + 1)) return true; return false; } } }; // Your WordDictionary object will be instantiated and called as such: // WordDictionary wordDictionary; // wordDictionary.addWord("word"); // wordDictionary.search("pattern");
相关文章推荐
- Java---IndexOf、LastIndexOf、Substring
- 安装RabbitVCS
- MFC批量修改文件名工具
- Java多线程(三)锁对象和线程池
- 试题系列五(公鸡5元一只,母鸡3元一只,小鸡1元3只,求100元刚好买100只鸡的可能)
- UI_03 ⾃定义视图、视图控制器
- 详解Android中AsyncTask的使用
- java程序员常用的工具名称--知道中文意思吗
- DFS csu1513 Kick the ball!
- [hdu5400 Arithmetic Sequence]预处理,容斥
- 网络硬件学习
- ZooKeeper3.4.6学习笔记(四)权限控制ACL
- 如何枚举PCIE capability
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 在ASP.NET Web API项目中使用Hangfire实现后台任务处理
- 好久没来了,重出江湖,共享个python34+pyqt+pyserial串口工具源码
- 【暑假】[深入动态规划]UVa 10618 Fixing the Great Wall
- NYOJ 2 括号配对问题 (栈 stack)
- 上传大文件,出现: 413 request Entity too Large错误的解决办法