472. 连接词


给你一个 不含重复 单词的字符串数组 words ,请你找出并返回 words 中的所有 连接词 。

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

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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

class Solution {

    private Trie trie;

    private boolean solve(String word, int index, boolean[] visited) {
        if (index == word.length()) {
            return true;
        }
        if (visited[index]) {
            return false;
        }
        Trie.Node cur = trie.getRoot();
        visited[index] = true;
        for (int i = index; i < word.length(); ++i) {
            int path = word.charAt(i) - 'a';
            if (cur.children[path] != null) {
                if (cur.children[path].end) {
                    if (solve(word, i + 1, visited)) {
                        return true;
                    }
                }
            } else {
                return false;
            }
            cur = cur.children[path];
        }
        return false;
    }

    public List findAllConcatenatedWordsInADict(String[] words) {
        this.trie = new Trie();
        Arrays.sort(words, new Comparator() {
            @Override
            public int compare(String o1, String o2) {
                return Integer.compare(o1.length(), o2.length());
            }
        });
        List ans = new ArrayList<>();
        for (int i = 0; i < words.length; ++i) {
            if (words[i].length() != 0) {
                if (solve(words[i], 0, new boolean[words[i].length()])) {
                    ans.add(words[i]);
                } else {
                    trie.insert(words[i]);
                }
            }
        }
        return ans;
    }
}

class Trie {

    private Node root = new Node();

    class Node {
        Node[] children = new Node[26];
        boolean end;
    }

    public void insert(String word) {
        Node cur = root;
        for (int i = 0; i < word.length(); ++i) {
            int path = word.charAt(i) - 'a';
            if (cur.children[path] == null) {
                cur.children[path] = new Node();
            }
            cur = cur.children[path];
        }
        cur.end = true;
    }

    public Node getRoot() {
        return root;
    }
}