File tree 1 file changed +53
-0
lines changed
1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change @@ -62,9 +62,62 @@ class Trie {
62
62
Node node = search(word);
63
63
return node != null && node. isLeaf;
64
64
}
65
+
65
66
boolean startsWith (String word ) {
66
67
Node node = search(word);
67
68
return node != null ;
68
69
}
69
70
}
70
71
```
72
+
73
+ ``` python
74
+ class Node :
75
+ def __init__ (self , character ):
76
+ self .character = character
77
+ self .children = {}
78
+ self .isLeaf = False
79
+
80
+ def __repr__ (self ):
81
+ return self .character + " -> " + str (self .children)
82
+
83
+ class Trie :
84
+ def __init__ (self ):
85
+ self .root = Node(" " )
86
+
87
+ def __str__ (self ):
88
+ return str (self .root)
89
+
90
+ def insert (self , word ):
91
+ children = self .root.children
92
+ for index, c in enumerate (word):
93
+ current = None
94
+ if c in children.keys():
95
+ current = children[c]
96
+ else :
97
+ current = Node(c)
98
+ children[c] = current
99
+
100
+ if index == len (word) - 1 :
101
+ current.isLeaf = True
102
+
103
+ children = current.children
104
+
105
+ def search (self , word ):
106
+ node = self .doSearch(word)
107
+ return node is not None and node.isLeaf
108
+
109
+ def startsWith (self , word ):
110
+ return self .doSearch(word) is not None
111
+
112
+ def doSearch (self , word ):
113
+ children = self .root.children
114
+ current = None
115
+ for c in word:
116
+ if c in children.keys():
117
+ current = children[c]
118
+ children = current.children
119
+ else :
120
+ current = None
121
+
122
+ return current
123
+ ```
You can’t perform that action at this time.
0 commit comments