class Trie:
def __init__(self):
self.children = [None] * 26
self.isEnd = False
# 根据插入的word构造字典树
def insert(self, word):
node = self
for ch in word:
ch = ord(ch) - ord("a")
if not node.children[ch]:
node.children[ch] = Trie()
node = node.children[ch]
node.isEnd = True
# 遍历word是否满足字典树
def dfs(self, word, start):
if start == len(word):
return True
node = self
for i in range(start, len(word)):
node = node.children[ord(word[i]) - ord("a")]
if node is None:
return False
if node.isEnd and self.dfs(word, i + 1):
return True
return False
def findAllConcatenatedWordsInADict(words):
words.sort(key=len)
ans = []
root = Trie()
for word in words:
if word == "":
continue
# 如果当前单词存在于字典树中,则是连接词
if root.dfs(word, 0):
ans.append(word)
# 否则加入到字典树中
else:
root.insert(word)
return ans
if __name__ == '__main__':
findAllConcatenatedWordsInADict(
["cat", "cats", "catsdogcats", "dog", "dogcatsdog", "hippopotamuses", "rat", "ratcatdogcat"])
把每一个words中的元word构建一个大的字典树,判断两次满足元单词的word加入到最终的结果中