class Solution(object):
def findAllConcatenatedWordsInADict(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
t = Trie()
ans = []
m = sorted(words,key = lambda i :len(i),reverse = False)
# print(m)
for word in m:
if word == "":
continue
if t.search(word):
ans.append(word)
else:
t.insert(word)
# print(t.child)
return ans
class Trie(object):
def __init__(self):
self.child = {}
def insert(self, word):
"""
:type word: str
:rtype: None
"""
nowsdata = self.child
for s in word:
if s not in nowsdata.keys():
nowsdata[s] = {}
nowsdata = nowsdata[s]
nowsdata['#'] = '#'
def search(self, word):
"""
:type word: str
:rtype: bool
"""
nowsdata = self.child
for i in range(len(word)):
if '#' in nowsdata:
if self.search(word[i:]): # 如果if不成立则接着执行for循环
return True
if word[i] not in nowsdata.keys():
return False
nowsdata = nowsdata[word[i]]
return '#' in nowsdata.keys()