Design a data structure that supports the following the Operations:addword (word) and 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.
Notice
You may assume this all words is consist of lowercase letters A-Z.
Example
Addword ("bad")
Addword ("Dad")
Addword ("Mad")
Search ("pad")//return False
Search ("bad")//return True
Search (". Ad")//return True
Search ("B..") return True
For the original topic on Leetcode, please see my previous blog add and Search word-data structure design.
classWorddictionary { Public: structTrienode {BOOLIsLeaf; Trienode*child[ -]; }; Worddictionary () {root=NewTrienode (); } //Adds A word into the data structure. voidAddword (stringword) {Trienode*p =Root; for(CharC:word) { inti = C-'a'; if(!p->child[i]) p->child[i] =NewTrienode (); P= p->Child[i]; } P->isleaf =true; } //Returns If the word is in the data structure. A Word could//contain the dot character '. ' to represent. BOOLSearchstringword) {Search (Word, root,0); } BOOLSearchstring&word, Trienode *p,inti) {if(i = = Word.size ())returnP->IsLeaf; if(Word[i] = ='.') { for(Auto a:p->Child ) { if(A && search (word, a, i +1))return true; } return false; } Else { returnP->child[word[i]-'a'] && Search (Word, p->child[word[i]-'a'], i +1); } }Private: Trienode*root;};
[Lintcode] Add and search word adding and finding words