472. Concatenated Words

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zjucor/article/details/82379031

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.

算法原型是判断一个string能不能由另外一个string里面的string组成

直观想法就是DFS,也可以用DP

class Solution:
    def findAllConcatenatedWordsInADict(self, words):
        """
        :type words: List[str]
        :rtype: List[str]
        """
        s=set(words)
        res=[]
        
        def helper(a):
            dp=[False]*(1+len(a))
            dp[0]=True
            for i in range(1,1+len(a)):
                for j in range(i):
                    if not dp[j]: continue
                    if a[j:i] in s:
                        dp[i]=True
                        break
            return dp[-1]
            
        for w in s:
            for j in range(1,len(w)):
                if w[:j] in s and helper(w[j:]):
                    res.append(w)
                    break
        return res
    

猜你喜欢

转载自blog.csdn.net/zjucor/article/details/82379031
今日推荐