class WordDictionary { private TreeNode root; public static class TreeNode{ private char data; private TreeNode[] child = new TreeNode[26]; private boolean isEndingChar = false; public TreeNode(char data){ this.data = data; } } /** Initialize your data structure here. */ public WordDictionary() { root = new TreeNode('/'); } /** Adds a word into the data structure. */ public void addWord(String word) { TreeNode node = root; char[] array = word.toCharArray(); for(int i = 0 ;i < array.length ; i++){ int index = array[i] - 'a'; if(node.child[index] == null){ node.child[index] = new TreeNode(array[i]); } node = node.child[index]; } node.isEndingChar = true; } /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ public boolean search(String word) { if(word == null || word.length() == 0){ return true; } TreeNode node = root; char[] array = word.toCharArray(); return helper(array,0,node); } public boolean helper(char[] array,int index,TreeNode node){ if(index == array.length){ return node.isEndingChar; } char data = array[index]; if(data == '.'){ TreeNode[] child = node.child; for(int i = 0 ; i< child.length ; i++){ if(child[i] != null && helper(array, index+1, child[i])){ return true; } } return false; }else{ int num = data - 'a'; if(node.child[num] == null){ return false; } return helper(array,index+1, node.child[num]); } } }
/** * Your WordDictionary object will be instantiated and called as such: * WordDictionary obj = new WordDictionary(); * obj.addWord(word); * boolean param_2 = obj.search(word); */