Leetcode - Word Break
Leetcode - First Bad Version

Leetcode - Concatenated Words

violet posted @ May 01, 2020 06:52:26 AM in 算法 with tags Algorithm DP Golang , 181 阅读

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:

  1. The number of elements of the given array will not exceed 10,000
  2. The length sum of elements in the given array will not exceed 600,000.
  3. All the input string will only include lower case letters.
  4. 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
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter