classSolution{classTreeNode{boolean isWord;
TreeNode[] next;publicTreeNode(){
isWord =false;
next =newTreeNode[26];}}publicbooleanfindInTree(String word, TreeNode root,int i){// 在字典树里面找某个单词是否出现过
TreeNode cur = root;for(; i < word.length(); i ++){int id = word.charAt(i)-'a';if(cur.next[id]== null){// 没有出现returnfalse;}else{// 出现过if(cur.next[id].isWord){// 且是完整单词if(i == word.length()-1)returntrue;boolean flag =findInTree(word, root, i +1);// 不要用substring的方法,比较慢if(flag)returntrue;}
cur = cur.next[id];}}returnfalse;}public List<String>findAllConcatenatedWordsInADict(String[] words){
Arrays.sort(words,newComparator<String>(){@Overridepublicintcompare(String a, String b){return a.length()- b.length();}});
List<String> ans =newArrayList<String>();
TreeNode root =newTreeNode();for(String s : words){if(findInTree(s, root,0)) ans.add(s);// 组合而来的单词不要加入字典树,否则会超时else{// 当前词语加入字典树
TreeNode cur = root;for(int i =0; i < s.length(); i ++){int id = s.charAt(i)-'a';if(cur.next[id]== null) cur.next[id]=newTreeNode();
cur = cur.next[id];}
cur.isWord =true;}}return ans;}}
classStreamChecker{classTrie{
Trie[] next;boolean isWord;publicTrie(){
next =newTrie[26];}}
Trie root;
Trie[] t;int num;publicvoidinsert(String word){
Trie cur = root;for(int i =0; i < word.length(); i ++){int id = word.charAt(i)-'a';if(cur.next[id]== null){
cur.next[id]=newTrie();}
cur = cur.next[id];}
cur.isWord =true;}publicStreamChecker(String[] words){
root =newTrie();for(int i =0; i < words.length; i ++){insert(words[i]);}
t =newTrie[40001];
num =0;}publicbooleanquery(char letter){int id =0;boolean flag =false;int k = letter -'a';for(int i =0; i < num; i ++){
Trie tmp = t[i].next[k];if(tmp == null)continue;
t[id]= tmp;if(tmp.isWord) flag =true;
id ++;}
t[id]= root.next[k];if(t[id]== null) num = id;else{if(t[id].isWord) flag =true;
num = id +1;}return flag;}}/**
* Your StreamChecker object will be instantiated and called as such:
* StreamChecker obj = new StreamChecker(words);
* boolean param_1 = obj.query(letter);
*/
472. 连接词class Solution { class TreeNode { boolean isWord; TreeNode[] next; public TreeNode() { isWord = false; next = new TreeNode[26]; } } public boolean findInTree(String word, TreeNo