class Solution(object):
# 思路:
# 先把句子按空格分成单词;
# 遍历每个单词中的字符,查看是否是词根,是则替换并遍历下一个单词。
def replaceWords(self, dictionary, sentence):
"""
:type dictionary: List[str]
:type sentence: str
:rtype: str
"""
listSen = sentence.split()
for index, word in enumerate(listSen):
temp = []
for j in word:
temp.append(j)
if ''.join(temp) in dictionary:
listSen[index] = ''.join(temp)
break
return ' '.join(listSen)
if __name__ == '__main__':
s = Solution()
print(s.replaceWords(dictionary=["a", "aa", "aaa", "aaaa"], sentence="a aa a aaaa aaa aaa aaa aaaaaa bbb baba ababa"))