zoukankan      html  css  js  c++  java
  • 字典树

    208. 实现 Trie (前缀树)

    难度中等

    实现一个 Trie (前缀树),包含 insertsearch, 和 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 构成的。
    • 保证所有输入均为非空字符串。
     1 class Trie:
     2 
     3     def __init__(self):
     4         """
     5         Initialize your data structure here.
     6         """
     7         self.root = {}
     8 
     9 
    10     def insert(self, word: str) -> None:
    11         """
    12         Inserts a word into the trie.
    13         """
    14         node = self.root
    15         for char in word:
    16             #setdefault()方法使用指定的键返回项目的值.如果键不存在,则插入这个具有指定值的键.
    17             node =  node.setdefault(char, {}) 
    18 
    19         node["end"] = True
    20 
    21 
    22     def search(self, word: str) -> bool:
    23         """
    24         Returns if the word is in the trie.
    25         """
    26         node = self.root
    27         for char in word:
    28             if char not in node:
    29                 return False
    30             node = node[char]
    31 
    32         return "end" in node
    33 
    34 
    35     def startsWith(self, prefix: str) -> bool:
    36         """
    37         Returns if there is any word in the trie that starts with the given prefix.
    38         """
    39         node =  self.root
    40         for char in prefix:
    41             if char not in node:
    42                 return False
    43             node = node[char]
    44         
    45         return True
    View Code

    插入apple与apply:

     {'a': {'p': {'p': {'l': {'e': {'end': True}}}}}}

     {'a': {'p': {'p': {'l': {'e': {'end': True}, 'y': {'end': True}}}}}}

    设计一个支持以下两种操作的数据结构:

    void addWord(word)
    bool search(word)
    

    search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一个字母。

    示例:

    addWord("bad")
    addWord("dad")
    addWord("mad")
    search("pad") -> false
    search("bad") -> true
    search(".ad") -> true
    search("b..") -> true
    

    说明:

    你可以假设所有单词都是由小写字母 a-z 组成的。

     1 class WordDictionary:
     2 
     3     def __init__(self):
     4         """
     5         Initialize your data structure here.
     6         """
     7         self.root = {}
     8 
     9 
    10     def addWord(self, word: str) -> None:
    11         """
    12         Adds a word into the data structure.
    13         """
    14         node = self.root
    15         for char in word:
    16             node = node.setdefault(char, {})
    17         
    18         node['end'] = True
    19 
    20 
    21     def search(self, word: str) -> bool:
    22         """
    23         Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
    24         """
    25         return self._dfs(self.root, word)
    26 
    27     def _dfs(self, dictionary, word):
    28 
    29         for index, char in enumerate(word):
    30             if char == '.':
    31                 res = 0
    32                 for any_char in dictionary:
    33                     if any_char != 'end':
    34                         temp_res = self._dfs(dictionary[any_char], word[index+1:]) 
    35                         res += temp_res
    36                 return res != 0
    37 
    38             elif char not in dictionary:
    39                 return False
    40                 
    41             else:
    42                 dictionary = dictionary[char]
    43 
    44         return 'end' in dictionary
    View Code
  • 相关阅读:
    BZOJ 2212/BZOJ 3702
    BZOJ 4761 Cow Navigation
    BZOJ 3209 花神的数论题
    BZOJ 4760 Hoof, Paper, Scissors
    BZOJ 3620 似乎在梦中见过的样子
    BZOJ 3940 Censoring
    BZOJ 3942 Censoring
    BZOJ 3571 画框
    BZOJ 1937 最小生成树
    BZOJ 1058 报表统计
  • 原文地址:https://www.cnblogs.com/dede-0119/p/12508839.html
Copyright © 2011-2022 走看看