-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathtrie_add_and_search.py
More file actions
82 lines (70 loc) · 2.22 KB
/
trie_add_and_search.py
File metadata and controls
82 lines (70 loc) · 2.22 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
"""
We are asked to design an efficient data structure
that allows us to add and search for words.
The search can be a literal word or regular expression
containing “.”, where “.” can be any letter.
Example:
addWord(“bad”)
addWord(“dad”)
addWord(“mad”)
search(“pad”) -> false
search(“bad”) -> true
search(“.ad”) -> true
search(“b..”) -> true
"""
import collections
class TrieNode:
def __init__(self, letter, is_terminal=False):
self.children = dict()
self.letter = letter
self.is_terminal = is_terminal
class WordDictionary:
def __init__(self):
self.root = TrieNode("")
def add_word(self, word):
cur = self.root
for letter in word:
if letter not in cur.children:
cur.children[letter] = TrieNode(letter)
cur = cur.children[letter]
cur.is_terminal = True
def search(self, word, node=None):
cur = node
if not cur:
cur = self.root
for i, letter in enumerate(word):
# if dot
if letter == ".":
if i == len(word) - 1: # if last character
return any(
child.is_terminal
for child in cur.children.itervalues()
)
return any(
self.search(word[i + 1 :], child)
for child in cur.children.itervalues()
)
# if letter
if letter not in cur.children:
return False
cur = cur.children[letter]
return cur.is_terminal
class WordDictionary2:
def __init__(self):
self.word_dict = collections.defaultdict(list)
def add_word(self, word):
if word:
self.word_dict[len(word)].append(word)
def search(self, word):
if not word:
return False
if "." not in word:
return word in self.word_dict[len(word)]
for v in self.word_dict[len(word)]:
# match xx.xx.x with yyyyyyy
for i, ch in enumerate(word):
if ch != v[i] and ch != ".":
break
else:
return True
return False