Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the WordDictionary class:
WordDictionary() Initializes the object.
void addWord(word) Adds word to the data structure, it can be matched later.
bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.
word in addWord consists of lowercase English letters.
word in search consist of '.' or lowercase English letters.
There will be at most 2 dots in word for search queries.
At most 104 calls will be made to addWord and search.
Solutions
Solution 1
Thinking
Exact lookup could use a hash set, but \(.\) matches any letter, so scanning every word is awkward. Words use lowercase letters, which fit a trie.
Add walks a \(26\)-way path. Search follows a fixed edge on a letter and branches over every non-empty child on \(.\); a match must end on a word node.
classTrie:def__init__(self):self.children=[None]*26self.is_end=FalseclassWordDictionary:def__init__(self):self.trie=Trie()defaddWord(self,word:str)->None:node=self.trieforcinword:idx=ord(c)-ord('a')ifnode.children[idx]isNone:node.children[idx]=Trie()node=node.children[idx]node.is_end=Truedefsearch(self,word:str)->bool:defsearch(word,node):foriinrange(len(word)):c=word[i]idx=ord(c)-ord('a')ifc!='.'andnode.children[idx]isNone:returnFalseifc=='.':forchildinnode.children:ifchildisnotNoneandsearch(word[i+1:],child):returnTruereturnFalsenode=node.children[idx]returnnode.is_endreturnsearch(word,self.trie)# Your WordDictionary object will be instantiated and called as such:# obj = WordDictionary()# obj.addWord(word)# param_2 = obj.search(word)
classTrie{Trie[]children=newTrie[26];booleanisEnd;}classWordDictionary{privateTrietrie;/** Initialize your data structure here. */publicWordDictionary(){trie=newTrie();}publicvoidaddWord(Stringword){Trienode=trie;for(charc:word.toCharArray()){intidx=c-'a';if(node.children[idx]==null){node.children[idx]=newTrie();}node=node.children[idx];}node.isEnd=true;}publicbooleansearch(Stringword){returnsearch(word,trie);}privatebooleansearch(Stringword,Trienode){for(inti=0;i<word.length();++i){charc=word.charAt(i);intidx=c-'a';if(c!='.'&&node.children[idx]==null){returnfalse;}if(c=='.'){for(Triechild:node.children){if(child!=null&&search(word.substring(i+1),child)){returntrue;}}returnfalse;}node=node.children[idx];}returnnode.isEnd;}}/** * Your WordDictionary object will be instantiated and called as such: * WordDictionary obj = new WordDictionary(); * obj.addWord(word); * boolean param_2 = obj.search(word); */
classtrie{public:vector<trie*>children;boolis_end;trie(){children=vector<trie*>(26,nullptr);is_end=false;}voidinsert(conststring&word){trie*cur=this;for(charc:word){c-='a';if(cur->children[c]==nullptr){cur->children[c]=newtrie;}cur=cur->children[c];}cur->is_end=true;}};classWordDictionary{private:trie*root;public:WordDictionary():root(newtrie){}voidaddWord(stringword){root->insert(word);}boolsearch(stringword){returndfs(word,0,root);}private:booldfs(conststring&word,inti,trie*cur){if(i==word.size()){returncur->is_end;}charc=word[i];if(c!='.'){trie*child=cur->children[c-'a'];if(child!=nullptr&&dfs(word,i+1,child)){returntrue;}}else{for(trie*child:cur->children){if(child!=nullptr&&dfs(word,i+1,child)){returntrue;}}}returnfalse;}};/** * Your WordDictionary object will be instantiated and called as such: * WordDictionary* obj = new WordDictionary(); * obj->addWord(word); * bool param_2 = obj->search(word); */
typeWordDictionarystruct{root*trie}funcConstructor()WordDictionary{returnWordDictionary{new(trie)}}func(this*WordDictionary)AddWord(wordstring){this.root.insert(word)}func(this*WordDictionary)Search(wordstring)bool{n:=len(word)vardfsfunc(int,*trie)booldfs=func(iint,cur*trie)bool{ifi==n{returncur.isEnd}c:=word[i]ifc!='.'{child:=cur.children[c-'a']ifchild!=nil&&dfs(i+1,child){returntrue}}else{for_,child:=rangecur.children{ifchild!=nil&&dfs(i+1,child){returntrue}}}returnfalse}returndfs(0,this.root)}typetriestruct{children[26]*trieisEndbool}func(t*trie)insert(wordstring){cur:=tfor_,c:=rangeword{c-='a'ifcur.children[c]==nil{cur.children[c]=new(trie)}cur=cur.children[c]}cur.isEnd=true}/** * Your WordDictionary object will be instantiated and called as such: * obj := Constructor(); * obj.AddWord(word); * param_2 := obj.Search(word); */