zoukankan      html  css  js  c++  java
  • [leetcode trie]211. Add and Search Word

    Design a data structure that supports the following two operations:

    void addWord(word)
    bool search(word)
    

    search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

    For example:

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


    实现字典树,其中search可以实现正则表达式中的.功能
    这个题重点在正则表达式,如果一个单词中第一个字符为. 那么就用.之后的所有字符和字典中的所有字典树进行匹配
     1 class WordDictionary(object):
     2 
     3     def __init__(self):
     4         self.root = {}
     5         
     6 
     7     def addWord(self, word):
     8         cur = self.root
     9         for c in word:
    10             cur  = cur.setdefault(c,{})
    11         cur[None] = None
    12         
    13 
    14     def search(self, word):
    15         def find(word,node):
    16             if not word:
    17                 return None in node
    18             c,w = word[0],word[1:]
    19             if c != '.':
    20                 return c in node and find(w,node[c])
    21             return any(find(w,nd) for nd in node.values() if nd)
    22         return find(word,self.root)

    不明白为什么设置node.is_word会错误。。

  • 相关阅读:
    Restful 的概念预览
    Bootstrap中alerts的用法
    Bootstrap HTML编码规范总结
    Bootstrap中img-circle glyphicon及js引入加载更快的存放位置
    PI数据库
    memcached
    Bootstrap中样式Jumbotron,row, table的实例应用
    js事件监听
    jquery显示隐藏操作
    HDU4521+线段树+dp
  • 原文地址:https://www.cnblogs.com/fcyworld/p/6516556.html
Copyright © 2011-2022 走看看