classWordDictionary{ classNode{ Node[] next; boolean isWord; publicNode(){ next = new Node[26]; }; } Node root = new Node(); /** Initialize your data structure here. */ publicWordDictionary(){ } /** Adds a word into the data structure. */ publicvoidaddWord(String word){ Node p = root; for (char c: word.toCharArray()) { if (p.next[c-'a'] == null) { p.next[c-'a'] = new Node(); } p = p.next[c-'a']; } p.isWord = 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 find(word, root); } publicbooleanfind(String word, Node p){ for (int i=0; i<word.length(); i++) { char c = word.charAt(i); if (c>='a' && c<='z') { if (p.next[c-'a'] == null) { returnfalse; } p = p.next[c-'a']; } else { boolean find = false; for (Node n: p.next) { if (n != null) { find = (find || find(word.substring(i+1), n)); } } return find; } } return p.isWord; } }
/** * Your WordDictionary object will be instantiated and called as such: * WordDictionary obj = new WordDictionary(); * obj.addWord(word); * boolean param_2 = obj.search(word); */