题目

Design a data structure that supports the following two operations:

1
2
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.

Example:

1
2
3
4
5
6
7
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

Note:
You may assume that all words are consist of lowercase letters a-z.

Python3:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class WordDictionary:

def __init__(self):
"""
Initialize your data structure here.
"""


def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""


def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
"""



# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)

题解

题意:
完成WordDictionary类,addWord方法向词库中添加词,search方法用来搜索词,其中 ‘.’ 表示该位置可匹配任意字符. 所有单词只包含小写字母.

思路:
创建一颗树,在单词结尾节点进行标记以判断是否单词,遇到 ‘.’ 则对当前节点的所有子节点进行匹配.

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import collections as cl
class Node:
def __init__(self):
self.Children=cl.defaultdict(Node)
self.isWord=False

class WordDictionary:

def __init__(self):
self.root=Node()
"""
Initialize your data structure here.
"""

def addWord(self, word: str) -> None:
node = self.root
for i in word:
node =node.Children[i]
node.isWord=True #对单词结尾标记
"""
Adds a word into the data structure.
"""

def search(self, word: str) -> bool:
node = self.root
self.res=False
self.dfs(node,word)
return self.res

"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
"""

def dfs(self,node,word):
if not word:
if node.isWord:
self.res = True
return
else :
return
if word[0]=='.':
for j in node.Children.values():
self.dfs(j,word[1:])
else :
node = node.Children.get(word[0])
if not node:
return
self.dfs(node,word[1:])

# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)