[LeetCode]211 添加与搜索单词-数据结构设计

题目描述

设计一个支持以下两种操作的数据结构:

void addWord(word)
bool search(word)

search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 .a-z. 可以表示任何一个字母。

示例:

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

代码

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
class WordDictionary:

def __init__(self):
"""
Initialize your data structure here.
"""
from collections import defaultdict
self.word_dict = defaultdict(list)


def addWord(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: void
"""
self.word_dict[len(word)].append(word)


def search(self, word):
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool
"""
for item in self.word_dict[len(word)]:
flag = False
for x,y in zip(item,word):
if y == "." or x == y:
continue
else:
flag = True
break
if not flag :
return True
return False