Implement Trie (Prefix Tree)前缀树系列

208. Implement Trie (Prefix Tree)  

class Trie:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.tree = []
        

    def insert(self, word: str) -> None:
        """
        Inserts a word into the trie.
        """
        self.tree.append(word)
        
        

    def search(self, word: str) -> bool:
        """
        Returns if the word is in the trie.
        """
        return word in self.tree
        

    def startsWith(self, prefix: str) -> bool:
        """
        Returns if there is any word in the trie that starts with the given prefix.
        """
        for item in self.tree:
            if item.startswith(prefix):
                return True
        return False
            

648. Replace Words

class Solution:
    def replaceWords(self, roots: List[str], sentence: str) -> str:
        new_dic = {}
        for root in roots:
            length = len(root)
            new_dic[root] = length
        new_dic = sorted(new_dic.keys())
        sentence = sentence.split()
        new_sentence = sentence.copy()
        for root in new_dic:
            for i  in range(len(sentence)):
                if sentence[i][:len(root)] == root:
                    sentence[i] = "1"
                    new_sentence[i] = root
        output = ""
        for word in new_sentence:
            output  = output + " " + word
                  
        return output.lstrip()

 676. Implement Magic Dictionary  这个题可能是我AC的最好的一个题了 

Runtime: 20 ms, faster than 99.81% of Python3 online submissions for Implement Magic Dictionary.

Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Implement Magic Dictionary.

class MagicDictionary:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.roots = []
        

    def buildDict(self, root: List[str]) -> None:
        """
        Build a dictionary through a list of words
        """
        self.roots += root
        
        

    def search(self, word: str) -> bool:
        """
        Returns if there is any word in the trie that equals to the given word after modifying exactly one character
        """
        res = [0]
        for root in self.roots:
            if len(root) == len(word):
                temp = 0
                for i in range(len(root)):
                    if root[i] != word[i]:
                        temp +=1
                res.append(temp)
        if len(res) == 1:
            return False
        if 1 in res :
            return True
        else:
            return False
                        

 

677. Map Sum Pairs 这个题AC的效果也比较好

Runtime: 32 ms, faster than 92.23% of Python3 online submissions for Map Sum Pairs.

Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Map Sum Pairs.

class MapSum:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.dic = {}
        

    def insert(self, key: str, val: int) -> None:
        self.dic[key] = val
        

    def sum(self, prefix: str) -> int:
        res = 0
        for key in self.dic.keys():
            if key.startswith(prefix):
                res += self.dic[key]
                
        return res

 

发布了42 篇原创文章 · 获赞 6 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/zkyxgs518/article/details/103018173
今日推荐