zoukankan      html  css  js  c++  java
  • 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
    

      

  • 相关阅读:
    python3随记——字符编码
    python基础3(元祖、字典、深浅copy、集合、文件处理)
    python的颜色显示
    python基础2(数据类型、数据运算、for循环、while循环、列表)
    python基础之初始python
    0423作业(函数)
    0423上课练习(list、while、def)
    函数的定义与调用(4.23)
    0422作业:基础(if,while)
    while,for,if输入账号密码判断(还请各位大牛能够优化,本人刚学习一周)
  • 原文地址:https://www.cnblogs.com/bonelee/p/12583851.html
Copyright © 2011-2022 走看看