Tire 字典树

Posted bonelee

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Tire 字典树相关的知识,希望对你有一定的参考价值。

648. 单词替换

难度中等

在英语中,我们有一个叫做 词根(root)的概念,它可以跟着其他一些词组成另一个较长的单词——我们称这个词为 继承词(successor)。例如,词根an,跟随着单词 other(其他),可以形成新的单词 another(另一个)。

现在,给定一个由许多词根组成的词典和一个句子。你需要将句子中的所有继承词词根替换掉。如果继承词有许多可以形成它的词根,则用最短的词根替换它。

你需要输出替换之后的句子。

示例 1:

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

注:

  1. 输入只包含小写字母。
  2. 1 <= 字典单词数 <=1000
  3. 1 <=  句中词语数 <= 1000
  4. 1 <= 词根长度 <= 100
  5. 1 <= 句中词语长度 <= 1000

 

用最笨的方法居然也给过了!!!

class Solution(object):
    def replaceWords(self, dict, sentence):
        """
        :type dict: List[str]
        :type sentence: str
        :rtype: str
        """
        trie = Trie()        
        for w in dict:
            trie.add_word(w)
        words = sentence.split()
        return " ".join([trie.find_neareast(word) for word in words])

        """        
        dict2 = {w for w in dict}
        words = sentence.split()
        return " ".join([self.replace(word, dict2) for word in words])
        """

    def replace(self, word, dict2):
        for i in range(1, len(word)+1):
            if word[:i] in dict2:
                return word[:i]
        return word


class Node(object):
    def __init__(self, char="", word=""):
        self.char = char
        self.word = word
        self.children = {}


class Trie(object):
    def __init__(self):
        self.root = Node()
    
    def add_word(self, word):
        cur = self.root
        for w in word:
            if w not in cur.children:
                cur.children[w] = Node(w)
            cur = cur.children[w]
        cur.word= word        
    
    def find_neareast(self, word):
        cur = self.root
        for w in word:        
            if cur.word:
                return cur.word                
            if w not in cur.children:
                return word            
            cur = cur.children[w]
        return word

  

 

 

以上是关于Tire 字典树的主要内容,如果未能解决你的问题,请参考以下文章

tire 学习心得

The XOR Largest Pair(Tire字典树应用)

Tire树高效统计字符串

字典树

字典树模板

字典树