[LC] 472. Concatenated Words

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".

Solution1: TLE
class Solution {
    public List<String> findAllConcatenatedWordsInADict(String[] words) {
        Arrays.sort(words, (a, b) -> a.length() - b.length());
        List<String> res = new ArrayList<>();
        List<String> wordList = new ArrayList<>();
        for (String str: words) {
            if (helper(str, wordList)) {
                res.add(str);
            }
            wordList.add(str);
        }
        return res;
    }
    
    private boolean helper(String str, List<String> list) {
        boolean[] boolArr = new boolean[str.length() + 1];
        for (int i = 1; i < boolArr.length; i++) {
            if (list.contains(str.substring(0, i))) {
                boolArr[i] = true;
                continue;
            }
            for (int j = 0; j < i; j++) {
                if (boolArr[j] && list.contains(str.substring(j, i))) {
                    boolArr[i] = true;
                    break;
                }
            }
        }
        return boolArr[str.length()];
    }
}

猜你喜欢

转载自www.cnblogs.com/xuanlu/p/12695541.html
今日推荐