Design a data structure that supports the following and the 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"), Falsesearch ("bad"), Truesearch (". Ad") Truesearch ("B..")-True
This problem with set can be timed out, you should define the data structure, construct a word number, so more efficient, in the search is DFS, the code is as follows:
1 classWorddictionary {2 Public:3 structtreenode{4 Public:5TreeNode *child[ -];6 BOOLIsword;7 8TreeNode (): Isword (false){9 for(Auto &a:child)TenA =NULL; One } A }; - - worddictionary () { theRoot =NewTreeNode (); - } - - //Adds A word into the data structure. + voidAddword (stringword) { -TreeNode * p =Root; + for(Auto &A:word) { A if(!p->child[a-'a']) atp->child[a-'a'] =NewTreeNode; -p = p->child[a-'a']; - } -P->isword =true;//Mark a Word - } - in - BOOLSearchword (string& Word, TreeNode * p,intindex) to { + if(word.size () = = index)returnp->isword;//This is a very important one . - if(Word[index] = ='.'){ the for(Auto & a:p->Child ) { * if(A && Searchword (Word, A, index+1))return true; $ }Panax Notoginseng return false;//don't forget. -}Else{ the return(P->child[word[index]-'a']) &&searchword (Word, p->child[word[index]-'a'], index+1); + } A } the + $ BOOLSearchstringword) { - returnSearchword (Word, root,0); - } the - Wuyi the - //worddictionary ()//Constructors are executed first after entering the function Wu //: Root (New TreeNode) {} - Private: AboutTreeNode *Root; $};
It's a little messy, forgive me.
Leetcode Oj:add and search Word-data structure design (adding and searching for words)