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
Public classWorddictionary {//the transformation of the dictionary tree, each node holds a character, and a collection of child nodes: list, and whether the tag is a isend Boolean of the tail node//both the Add and search methods are implemented using recursion PrivateNode Root; Static classnode{ PublicCharacter Val; PublicList<node>children; Public BooleanIsend; PublicNode (Character val) { This. val=Val; Children=NewArraylist<node>(); Isend=false; } } PublicWorddictionary () {root=NewNode ('/'); } //Adds A word into the data structure. Public voidAddword (String word) {Addword (word,root); } Public voidAddword (String word,node root) {if(Word.length () ==0) {Root.isend=true; return ; } Node cur=NULL;//represents a matching new node if(Root.children.size () >0){ for(Node node:root.children) {if(Node.val==word.charat (0) ) {cur=node; Break; } } } if(cur!=NULL) Addword (word.substring (1), cur); Else{cur=NewNode (Word.charat (0)); Root.children.add (cur); Addword (Word.substring (1), cur); } } //Returns If the word is in the data structure. A Word could//contain the dot character '. ' to represent. Public BooleanSearch (String word) {returnsearch (word,root); } Private BooleanSearch (String word,node root) {if(Word.length () ==0){ returnroot.isend==true; } if(root.children==NULL)return false; if(Word.charat (0) = = '. '){ for(Node node:root.children) {BooleanRet=search (word.substring (1), node); if(ret)return true; } return false; }Else{ for(Node node:root.children) {if(Node.val==word.charat (0)){ returnSearch (word.substring (1), node); } } return false; } }}//Your Worddictionary object would be instantiated and called as such://worddictionary worddictionary = new Worddictionary ();//Worddictionary.addword ("word");//Worddictionary.search ("pattern");
[Leedcode 211] ADD and Search word-data structure design