zoukankan      html  css  js  c++  java
  • [LeetCode] 208. 实现 Trie (前缀树)

    题目链接:https://leetcode-cn.com/problems/implement-trie-prefix-tree/

    题目描述:

    实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。

    示例:

    Trie trie = new Trie();
    
    trie.insert("apple");
    trie.search("apple");   // 返回 true
    trie.search("app");     // 返回 false
    trie.startsWith("app"); // 返回 true
    trie.insert("app");   
    trie.search("app");     // 返回 true
    

    说明:

    • 你可以假设所有的输入都是由小写字母 a-z 构成的。
    • 保证所有输入均为非空字符串。

    思路:

    前缀树,又称字典树

    详细可以查看

    多种写法,写个简单的!

    class Trie:
    
        def __init__(self):
            """
            Initialize your data structure here.
            """
            self.lookup = {}
            
    
        def insert(self, word: str) -> None:
            """
            Inserts a word into the trie.
            """
            tree = self.lookup
            for a in word:
                if a not in tree:
                    tree[a] = {}
                tree = tree[a]
            tree["#"] = "#"
            
    
        def search(self, word: str) -> bool:
            """
            Returns if the word is in the trie.
            """
            tree = self.lookup
            for a in word:
                if a not in tree:
                    return False
                tree = tree[a]
            if "#" in tree:
                return True
            return False
            
    
        def startsWith(self, prefix: str) -> bool:
            """
            Returns if there is any word in the trie that starts with the given prefix.
            """
            tree = self.lookup
            for a in prefix:
                if a not in tree:
                    return False
                tree = tree[a]
            return True
            
    
  • 相关阅读:
    Tensor总结
    Tensorflow池化
    conda操作
    KS值计算
    supervisor实践
    npm/yarn实践
    nni 环境搭建
    阿里云个人邮箱配置
    Jinja2宏使用
    利用VS code 远程调试 docker 中的 dotnet 应用
  • 原文地址:https://www.cnblogs.com/powercai/p/11385112.html
Copyright © 2011-2022 走看看