LeetCode_472、连接词

给定一个不含重复单词的列表,编写一个程序,返回给定单词列表中所有的连接词。

连接词的定义为:一个字符串完全是由至少两个给定数组中的单词组成的。

示例:

输入: [“cat”,“cats”,“catsdogcats”,“dog”,“dogcatsdog”,“hippopotamuses”,“rat”,“ratcatdogcat”]

输出: [“catsdogcats”,“dogcatsdog”,“ratcatdogcat”]

解释: “catsdogcats"由"cats”, “dog” 和 "cats"组成;
“dogcatsdog"由"dog”, "cats"和"dog"组成;
“ratcatdogcat"由"rat”, “cat”, "dog"和"cat"组成。
说明:

给定数组的元素总数不超过 10000。
给定数组中元素的长度总和不超过 600000。
所有输入字符串只包含小写字母。
不需要考虑答案输出的顺序。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/concatenated-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

前缀树

class Solution {

    class TreeNode{
        TreeNode[] list = new TreeNode[26];
        boolean isEnd = false;
    }

    public void insert(TreeNode root,String[] words){
        for(String word : words){
            if(word==null || word.equals("")) continue;
            TreeNode temp = root;
            char[] array = word.toCharArray();
            for(int i=0;i<array.length;i++){
                int index = array[i]-'a';
                if(temp.list[index]==null){
                    TreeNode tp = new TreeNode();
                    temp.list[index] = tp;
                }
                temp = temp.list[index];
            }
            temp.isEnd = true;
        }
    }

    public boolean seach(TreeNode root, String word, int count, int index){
        TreeNode temp = root;
        for(int i=index;i<word.length();i++){
            int pos = word.charAt(i) - 'a';
            if(temp.list[pos] == null)
                return false;
            temp = temp.list[pos];
            if(temp.isEnd && seach(root, word, count+1, i+1))
                return true;
        }
        return count>0 && temp.isEnd;
    }

    public List<String> findAllConcatenatedWordsInADict(String[] words) {
        List<String> list = new ArrayList<String>();
        TreeNode root = new TreeNode();
        insert(root,words);
        for(String word : words){
            if(seach(root,word,0,0)){
                list.add(word);
            }      
        }
        return list;
    }
}

你可能感兴趣的:(LeetCode题解)