首页 > 代码库 > [leetcode trie]211. Add and Search Word - Data structure design

[leetcode trie]211. Add and Search Word - Data structure design

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

[leetcode trie]211. Add and Search Word - Data structure design