Given a list of words (without duplicates), please write a program that returns all concatenated words in the given list of words.
A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.
Example:
Input: ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
Output: ["catsdogcats","dogcatsdog","ratcatdogcat"]
Explanation:
"catsdogcats" can be concatenated by "cats", "dog" and "cats";
"dogcatsdog" can be concatenated by "dog", "cats" and "dog";
"ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".
Note:
The number of elements of the given array will not exceed10,000
The length sum of elements in the given array will not exceed600,000.
All the input string will only include lower case letters.
The returned elements order does not matter.
2. Implementation
(1) Trie + DFS
classSolution {classTrieNode {char val;boolean isWord;TrieNode childNode[];publicTrieNode() { childNode =newTrieNode[26]; } }classTrie {TrieNode root;publicTrie() { root =newTrieNode(); }publicvoidadd(String word) {if (word ==null||word.length() ==0) {return; }TrieNode curNode = root;for (char c :word.toCharArray()) {int index = c -'a';if (curNode.childNode[index] ==null) {curNode.childNode[index] =newTrieNode();curNode.childNode[index].val= c; } curNode =curNode.childNode[index]; }curNode.isWord=true; }publicbooleansearch(String word) {if (word ==null||word.length() ==0) {returnfalse; }TrieNode curNode = root;for (char c :word.toCharArray()) {int index = c -'a';if (curNode.childNode[index] ==null) {returnfalse; } curNode =curNode.childNode[index]; }returncurNode.isWord; } }publicList<String> findAllConcatenatedWordsInADict(String[] words) {List<String> res =newArrayList<>();if (words ==null||words.length==0) {return res; }Trie trie =newTrie();for (String word : words) {trie.add(word); }for (String word : words) {if (isConcatenatedWord(word,0,0, trie)) {res.add(word); } }return res; }publicbooleanisConcatenatedWord(String word,int index,int count,Trie trie) {// If we are at the end of the current word, check if count is equal to or greater than 1// A concatenated word should consist of at least two wordsif (index ==word.length() && count >=2) {returntrue; }TrieNode curNode =trie.root;for (int i = index; i <word.length(); i++) {int pos =word.charAt(i) -'a';if (curNode.childNode[pos] ==null) {returnfalse; }// if word[0...i] && word[i+1...n] are found in dict, then the current word is concatenated wordif (curNode.childNode[pos].isWord) {if (isConcatenatedWord(word, i +1, count +1, trie)) {returntrue; } } curNode =curNode.childNode[pos]; }returnfalse; }}