Implement a magic directory with buildDict, and search methods.
For the method buildDict, you’ll be given a list of non-repetitive words to build a dictionary.
For the method search, you’ll be given a word, and judge whether if you modify exactly one character into another character in this word, the modified word is in the dictionary you just built.
You may assume that all the inputs are consist of lowercase letters a-z.
For contest purpose, the test data is rather small by now. You could think about highly efficient algorithm after the contest.
Please remember to RESET your class variables declared in class MagicDictionary, as static/class variables are persisted across multiple test cases. Please see here for more details.
classMagicDictionary{ TrieNode root; publicMagicDictionary(){ root = new TrieNode(); } /** Build a dictionary through a list of words */ publicvoidbuildDict(String[] dict){ for (String s: dict) { TrieNode node = root; for (char c: s.toCharArray()) { if (node.children[c - 'a'] == null) { node.children[c - 'a'] = new TrieNode(); } node = node.children[c - 'a']; } node.isWord = true; } } /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */ publicbooleansearch(String word){ char[] wordArray = word.toCharArray(); for (int i = 0; i < word.length(); i++) { for (char c = 'a'; c <= 'z'; c++) { if (wordArray[i] == c) { continue; } char pre = wordArray[i]; wordArray[i] = c; if (isWord(new String(wordArray), root)) { returntrue; } wordArray[i] = pre; } } returnfalse; } privatebooleanisWord(String s, TrieNode root){ TrieNode node = root; for (char c: s.toCharArray()) { if (node.children[c - 'a'] == null) { returnfalse; } node = node.children[c - 'a']; } return node.isWord; } }
classTrieNode{ TrieNode[] children = new TrieNode[26]; boolean isWord; publicTrieNode(){}; }
/** * Your MagicDictionary object will be instantiated and called as such: * MagicDictionary obj = new MagicDictionary(); * obj.buildDict(dict); * boolean param_2 = obj.search(word); */