当前位置 : 主页 > 网页制作 > HTTP/TCP >

[LeetCode] 208. 实现 Trie (前缀树)

来源:互联网 收集:自由互联 发布时间:2021-06-16
题目链接:https://leetcode-cn.com/problems/implement-trie-prefix-tree/ 题目描述: 实现一个 Trie (前缀树),包含 insert , search , 和 startsWith 这三个操作。 示例: Trie trie = new Trie();trie.insert("apple");tri

题目链接: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
网友评论