classWordDictionary{ TrieNode root; /** Initialize your data structure here. */ publicWordDictionary(){ root=new TrieNode(); } /** Adds a word into the data structure. */ publicvoidaddWord(String word){ TrieNode p=root; for(char ch:word.toCharArray()){ if(p.children[ch-'a']==null) p.children[ch-'a']=new TrieNode(); p=p.children[ch-'a']; } p.isWordEnd=true; } /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ publicbooleansearch(String word){ return match(word.toCharArray(),0,root); } privatebooleanmatch(char[] chs,int k,TrieNode p){ if(k==chs.length) return p.isWordEnd; if(chs[k]=='.'){ for(int i=0;i<26;i++){ if(p.children[i]!=null&&match(chs,k+1,p.children[i])) returntrue; } }else{ return p.children[chs[k]-'a']!=null&&match(chs,k+1,p.children[chs[k]-'a']); } returnfalse; } }
/** * Your WordDictionary object will be instantiated and called as such: * WordDictionary obj = new WordDictionary(); * obj.addWord(word); * boolean param_2 = obj.search(word); */