[Leetcode]648.Replace Words

Links: LeetCode648

In English, there is a concept of radical (root) is called, it may be followed by other long-word another word - we call this word for word inheritance (successor). For example, the root an, followed by the word other (other), can form a new word another (another).

Now, given a dictionary and a sentence consisting of many roots. All you need to inherit word in the sentence is replaced by root. If the word has many inherited form its root, it is replaced by the shortest root.

You need to output sentence after the replacement.

Example 1:

输入: dict(词典) = ["cat", "bat", "rat"]
sentence(句子) = "the cattle was rattled by the battery"
输出: "the cat was rat by the bat"

Related tags: dictionary tree

Find a match for more than one word, the dictionary tree is commonly used optimization algorithm. Here we only need to implement a getRoot () method in the dictionary tree, used to determine whether the current word has a corresponding root. If so, the corresponding root replacement, if not, will remain unchanged.
code show as below:

python:

import collections
class Node:
    def __init__(self):
        self.children = collections.defaultdict(lambda:Node())
        self.isWord = False
class Trie:
    def __init__(self):
        self.root = Node()

    def insert(self, word):
        current = self.root
        for w in word:
            current = current.children[w]
        current.isWord = True

    def getRoot(self,word):
        current = self.root
        for i,w in enumerate(word):
            if current.isWord:
                return word[:i]
            if w not in current.children:
                return word
            current = current.children[w]
        return word

class Solution:
    def replaceWords(self, dict: List[str], sentence: str) -> str:
        tree = Trie()
        for word in dict:
            tree.insert(word)
        res = []
        for word in sentence.split():
            res.append(tree.getRoot(word))
        return ' '.join(res)

Guess you like

Origin www.cnblogs.com/hellojamest/p/12236747.html