Add and Search Word - Data Structure Design
Design a data structure that supports the following two operations:
void addWord(word) bool 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.
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.
1 class TrieNode{ 2 public: 3 TrieNode* childNode[27]; 4 bool isVal; 5 TrieNode(){ 6 isVal = false; 7 for(int i = 0; i < 27; i++) 8 childNode[i] = NULL; 9 } 10 }; 11 class WordDictionary { 12 private: 13 TrieNode* root; 14 public: 15 WordDictionary(){ 16 root = new TrieNode(); 17 } 18 // Adds a word into the data structure. 19 void addWord(string word) { 20 TrieNode* temp = root; 21 for(int i = 0; i < word.size(); i++){ 22 int index = word[i] - 'a'; 23 if(word[i] == '.') 24 index = 26; 25 else{ 26 if(temp->childNode[index] == NULL) 27 temp->childNode[index] = new TrieNode(); 28 } 29 temp = temp->childNode[index]; 30 } 31 temp->isVal = true; //word has been inserted 32 } 33 34 // Returns if the word is in the data structure. A word could 35 // contain the dot character '.' to represent any one letter. 36 bool search(string word) { 37 return levelSearch(word, root, 0); 38 } 39 40 bool levelSearch(string& word, TrieNode* root, int index){ 41 TrieNode* temp = root; 42 if(!temp) return false; //length of the word is larger than that of the strings in the trie 43 if(index >= word.size()) return temp->isVal; 44 45 if(word[index] != '.') 46 return levelSearch(word, temp->childNode[word[index] - 'a'], index + 1); 47 else{ 48 for(int i = 0; i < 26; i++) 49 if(levelSearch(word, temp->childNode[i], index + 1)) return true; 50 return false; 51 } 52 } 53 }; 54 55 // Your WordDictionary object will be instantiated and called as such: 56 // WordDictionary wordDictionary; 57 // wordDictionary.addWord("word"); 58 // wordDictionary.search("pattern");