648. 單詞替換
在英語中,我們有一個叫做詞根(root)的概念,它可以跟著其他一些片語成另一個較長的單詞——我們稱這個詞為繼承詞(successor)。例如,詞根an,跟隨著單詞other(其他),可以形成新的單詞another(另一個)。
現在,給定一個由許多詞根組成的詞典和一個句子。你需要將句子中的所有繼承詞用詞根替換掉。如果繼承詞有許多可以形成它的詞根,則用最短的詞根替換它。
你需要輸出替換之後的句子。
示例 1:
輸入:dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
輸出:"the cat was rat by the bat"
示例 2:
輸入:dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs"
輸出:"a a b c"
示例 3:
輸入:dictionary = ["a", "aa", "aaa", "aaaa"], sentence = "a aa a aaaa aaa aaa aaa aaaaaa bbb baba ababa"
輸出:"a a a a a a a a bbb baba a"
示例 4:
輸入:dictionary = ["catt","cat","bat","rat"], sentence = "the cattle was rattled by the battery"
輸出:"the cat was rat by the bat"
示例 5:
輸入:dictionary = ["ac","ab"], sentence = "it is abnormal that this solution is accepted"
輸出:"it is ab that this solution is ac"
提示:
1 <= dictionary.length<= 1000
1 <= dictionary[i].length <= 100
dictionary[i]僅由小寫字母組成。
1 <= sentence.length <= 10^6
sentence僅由小寫字母和空格組成。
sentence 中單詞的總量在範圍 [1, 1000] 內。
sentence 中每個單詞的長度在範圍 [1, 1000] 內。
sentence 中單詞之間由一個空格隔開。
sentence沒有前導或尾隨空格。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/replace-words
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
class Solution: def replaceWords(self, dictionary: List[str], sentence: str) -> str: sentence=list(sentence.split()) res=[] for i in sentence: swap=[] for j in dictionary: if i.startswith(j): swap.append(j) if not swap: res.append(i) else: res.append(min(swap)) return ' '.join(res)
class Solution(object): def replaceWords(self, roots, sentence): """ :type dict: List[str] :type sentence: str :rtype: str """ # Because the default constructor registered by defaultdict is only called when it is called for the first time, so you can define yourself here. # Trie is a function, calling it will return a defaultdict Trie = lambda:collections.defaultdict(Trie) # tri first calls Trie, returns a defalutdict, so tri is a defalutdict tri = Trie() END = True for root in roots: # dict.__getitem__ requires two parameters, the first is the dictionary object, the second is the key # At the beginning, the dictionary object is tri, the key is the first character c of root, and tri[c] will return a new dictionary. # New dictionary represents the child node of the node starting with the character c # By analogy, finally get a leaf node, it should be empty by default, we assign the value of the whole word to the place where the key is END reduce(dict.__getitem__, root, tri)[END] = root def replace(word): cur = tri for c in word: # Either this character is not in the successor node of the current node, or has encountered the shortest prefix if c not in cur or END in cur:break # Otherwise continue to traverse down cur = cur[c] # When returning, there are two possibilities. If cur does not have a corresponding prefix, then the word does not match the word, and the word is returned. # get operation does not affect the value of Trie return cur.get(END, word)