classTrieNode:def__init__(self, val=None, isEnd=False):
self.val = val
self.isEnd = isEnd
self.children ={}#子字典树classSolution:defreplaceWords(self,dict, sentence):definsertWord(word):
cur = root #重置跟踪指针for w in word:#逐字母插入字典树if w notin cur.children:
cur.children[w]= TrieNode(w,False)
cur = cur.children[w]#切换跟踪指针
cur.isEnd =Truedeffind(word):#查找是否存在词根可以替换
cur = root #重置跟踪指针
res =[]for w in word:if cur.isEnd:#在有词根可以替换的条件下,遇到结束符号将现有词根返回return''.join(res)if w notin cur.children:#没有匹配到相应词根,返回原词return word
res.append(w)#将匹配到的字母暂时放置在res中
cur = cur.children[w]#切换跟踪指针到子字典树中else:#此用法,当for正常结束后会执行else,for中如果break了就不会执行else了,这是单词与词根同词的情况,不能通过for中的return进行返回,就需要另外的return分支了return''.join(res)
root = TrieNode('')for word indict:#遍历词根,插入字典中
insertWord(word)#替换操作
words = sentence.split()#将句子按空格切分
res =[]for word in words:
res.append(find(word))return' '.join(res)