zoukankan      html  css  js  c++  java
  • [leetcode trie]208. Implement Trie (Prefix Tree)

    实现一个字典树

     1 class Trie(object):
     2 
     3     def __init__(self):
     4         self.root = TrieNode()
     5 
     6     def insert(self, word):
     7         cur = self.root
     8         for i in word:
     9             cur = cur.children[i]
    10         cur.is_word = True
    11         
    12 
    13     def search(self, word):
    14         cur = self.root
    15         for i in word:
    16             cur = cur.children.get(i)
    17             if cur is None:
    18                 return False
    19         return cur.is_word
    20 
    21     def startsWith(self, prefix):
    22         cur = self.root
    23         for i in prefix:
    24             cur = cur.children.get(i)
    25             if cur is None:
    26                 return False
    27         return True
    28         
    29 class TrieNode(object):
    30     def __init__(self):
    31         self.children = collections.defaultdict(TrieNode)
    32         self.is_word = False
  • 相关阅读:
    GUI常用监听事件
    GUI容器之布局管理器
    布局管理器的综合应用
    GUI容器之Panel
    mongodb
    redis持久化
    本地window启动redis
    redis主从模式
    hash 哈希
    set集合
  • 原文地址:https://www.cnblogs.com/fcyworld/p/6512724.html
Copyright © 2011-2022 走看看