24
24
class TrieNode :
25
25
def __init__ (self ):
26
26
self .children = {}
27
- self .is_word = False
27
+ self .is_end = False
28
28
29
29
class WordDictionary (object ):
30
30
@@ -33,24 +33,41 @@ def __init__(self):
33
33
Initialize your data structure here.
34
34
"""
35
35
self .root = TrieNode ()
36
-
37
36
38
37
def addWord (self , word ):
39
38
"""
40
39
Adds a word into the data structure.
41
40
:type word: str
42
41
:rtype: void
43
42
"""
44
- if not word :
45
- return
46
-
47
43
node = self .root
48
- for w in word :
49
- if w not in node .children :
50
- node .children [w ] = TrieNode ()
51
-
52
- node = node .children [w ]
53
- node .is_word = True
44
+ for c in word :
45
+ if c not in node .children :
46
+ tmp = TrieNode ()
47
+ node .children [c ] = tmp
48
+ node = node .children [c ]
49
+ node .is_end = True
50
+
51
+
52
+ def find (self , root , word ):
53
+ node = root
54
+ for i in xrange (len (word )):
55
+ if word [i ] == '.' :
56
+ flag = False
57
+ for x in node .children :
58
+ if self .find (node .children [x ], word [i + 1 :]):
59
+ flag = True
60
+ break
61
+ if flag :
62
+ return True
63
+ else :
64
+ return False
65
+ else :
66
+ if word [i ] not in node .children :
67
+ return False
68
+ node = node .children [word [i ]]
69
+
70
+ return node != None and node .is_end
54
71
55
72
def search (self , word ):
56
73
"""
@@ -59,25 +76,7 @@ def search(self, word):
59
76
:rtype: bool
60
77
"""
61
78
62
- if not word :
63
- return False
64
-
65
- self .res = False
66
- self .find (self .root , word )
67
- return self .res
68
-
69
- def find (self , node , word ):
70
- if not word :
71
- if node .is_word :
72
- self .res = True
73
- return
74
- elif word [0 ] == '.' :
75
- for c in node .children :
76
- self .find (node .children [c ], word [1 :])
77
- else :
78
- if word [0 ] in node .children :
79
- self .find (node .children [word [0 ]], word [1 :])
80
-
79
+ return self .find (self .root , word )
81
80
82
81
83
82
# Your WordDictionary object will be instantiated and called as such:
0 commit comments