Leetcode - Concatenated Words
https://leetcode.com/problems/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".
Note:
-
The number of elements of the given array will not exceed
10,000
-
The length sum of elements in the given array will not exceed
600,000
. - All the input string will only include lower case letters.
- The returned elements order does not matter.
func findAllConcatenatedWordsInADict(words []string) []string { hash := map[string]bool{} for _, w := range words { hash[w] = true } result := []string{} for _, w := range words { m := len(w) dp := make([]bool, m+1) dp[0] = true for i := 1; i < m+1; i++ { for j := i - 1; j >= 0; j-- { tmp := w[j:i] if dp[j] && tmp != w && hash[tmp] { dp[i] = true break } } } if dp[m] && len(w) > 0 { result = append(result, w) } } return result }