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".
作为一个新手,上来当然时暴力搜索啦,直接双循环。
思路就是,对每个items,求能够concatenate的数量,做成一个列表
class Solution(object):
def findAllConcatenatedWordsInADict(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
d={}
for items in words:
d[items]=0
for i in words:
if i in items:
d[items] +=1
res=[]
for i in d:
if d[i] >2: res.append(i)
return res
比较坑的地方在于,他是要完全不同的数据构成的,也就是不能又重复的。
这个还是放大神的思路上来吧,暂时没有比较好的思路。
应该是用深度优先搜索来!
class Solution(object):
def findAllConcatenatedWordsInADict(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
d = set(words)
def dfs(word):
for i in range(1, len(word)):
prefix = word[:i]
suffix = word[i:]
if prefix in d and suffix in d:
return True
if prefix in d and dfs(suffix):
return True
if suffix in d and dfs(prefix):
return True
return False
res = []
for word in words:
if dfs(word):
res.append(word)
return res