Implement typeahead. Given a string and a dictionary, return all words that contains the string as a substring. The dictionary will give at the initialize method and wont be changed. The method to find all words with given substring would be called multiple times.
Example
Given dictionary ={"Jason Zhang", "James Yu", "Bob Zhang", "Larry Shi"}
publicclassTypeahead {Trie t;// @param dict A dictionary of words dictpublicTypeahead(Set<String> dict) {// do initialize if necessary t =newTrie();for (String word : dict) {for (int i =0; i <word.length(); i++) {String sub =word.substring(i);t.insert(sub, word); } } }// @param str: a string// @return a list of wordspublicList<String> search(String str) {returnnewArrayList<>(t.prefix(str)); }}classTrie {TrieNode root;publicTrie() { root =newTrieNode(); }publicvoidinsert(String word,String phrase) {if (word ==null||word.isEmpty()) {return; }TrieNode last = root;for (int i =0; i <word.length(); i++) {TrieNode cur =last.children.get(word.charAt(i));if (cur ==null) { cur =newTrieNode();last.children.put(word.charAt(i), cur); }cur.wordList.add(phrase); last = cur; }last.end=true; }publicSet<String> prefix(String str) {Set<String> emptyList =newHashSet<>();if (str ==null||str.isEmpty()) {return emptyList; }TrieNode last = root;for (int i =0; i <str.length(); i++) {TrieNode cur =last.children.get(str.charAt(i));if (cur ==null) {return emptyList; } last = cur; }returnlast.wordList; }}classTrieNode {HashMap<Character,TrieNode> children =newHashMap<>();boolean end;Set<String> wordList =newHashSet<>();}