Note: You may assume that all words are consist of lowercase letters a-z.
click to show hint.
You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.
Solution
publicclassWordDictionary {TrieNode root;publicclassTrieNode {String val;Map<Character,TrieNode> map;publicTrieNode() { map =newHashMap<>(); } }publicWordDictionary() { root =newTrieNode(); }// Adds a word into the data structure.publicvoidaddWord(String word) {if (word !=null||word.length() >=1) {addWord(word,0, root); } }privatevoidaddWord(String word,int d,TrieNode current) {if (d ==word.length()) {current.val= word;return; }char c =word.charAt(d);if (!current.map.containsKey(c)) {current.map.put(c,newTrieNode()); }TrieNode node =current.map.get(c);addWord(word, d +1, node); }// Returns if the word is in the data structure. A word could// contain the dot character '.' to represent any one letter.publicbooleansearch(String word) {if (word ==null||word.length() ==0) {returnfalse; }returnsearch(word,0, root); }privatebooleansearch(String word,int d,TrieNode node) {if (d ==word.length()) {if (node.val==null) {returnfalse; }returntrue; }char c =word.charAt(d);if (c =='.') {for (TrieNode child :node.map.values()) {if (search(word, d +1, child)) {returntrue; } }returnfalse; } else {if (node.map.containsKey(c)) {returnsearch(word, d +1,node.map.get(c)); } else {returnfalse; } } }}// Your WordDictionary object will be instantiated and called as such:// WordDictionary wordDictionary = new WordDictionary();// wordDictionary.addWord("word");// wordDictionary.search("pattern");