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会错误。。

  • 相关阅读:
    MySQL学习--标量函数之日期函数
    MySQL学习-- case表达式
    音视频推流方法与工具使用
    音视频基础知识
    音视频测试点
    postman处理二进制流文件
    postman脚本之时间处理
    移动性能测试之adb内存相关
    Proxychains安装
    Valgrind的安装及简单使用
  • 原文地址:https://www.cnblogs.com/fcyworld/p/6516556.html
Copyright © 2011-2022 走看看