Problem Statement
(Source) Given a list of words, 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. - The returned elements order does not matter.
Solution
class Solution(object):
def findAllConcatenatedWordsInADict(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
st = set(words)
def helper(word):
sta = [0]
explored = {0}
n = len(word)
while sta:
left = sta.pop()
if left == n: return True
for right in xrange(left+1, n+1):
if word[left : right] in st and right not in explored and (right != n or left > 0):
sta.append(right)
explored.add(right)
return False
return [word for word in words if word and helper(word)]
本文介绍了一种算法,用于从给定的单词列表中找出所有能够由列表内其他单词组合而成的单词。例如,catdog可以由cat和dog组合而成。文中提供了一个Python实现的例子。

267

被折叠的 条评论
为什么被折叠?



