File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Trie {
2
+ var nodes : [ String : Trie ] = [ : ]
3
+ var isEndOfWord : Bool = false
4
+
5
+ init ( ) {
6
+
7
+ }
8
+
9
+ func insert( _ word: String ) {
10
+ if word. isEmpty {
11
+ isEndOfWord = true
12
+ return
13
+ }
14
+
15
+ let firstChar = String ( word. first!)
16
+ if nodes [ firstChar] == nil {
17
+ nodes [ firstChar] = Trie ( )
18
+ }
19
+ nodes [ firstChar] ? . insert ( String ( word. dropFirst ( ) ) )
20
+ }
21
+
22
+ func search( _ word: String ) -> Bool {
23
+ if word. isEmpty {
24
+ return isEndOfWord
25
+ }
26
+
27
+ guard let firstChar = word. first,
28
+ let node = nodes [ String ( firstChar) ] else {
29
+ return false
30
+ }
31
+
32
+ return node. search ( String ( word. dropFirst ( ) ) )
33
+ }
34
+
35
+ func startsWith( _ prefix: String ) -> Bool {
36
+ if prefix. isEmpty {
37
+ return true
38
+ }
39
+
40
+ guard let firstChar = prefix. first,
41
+ let node = nodes [ String ( firstChar) ] else {
42
+ return false
43
+ }
44
+ return node. startsWith ( String ( prefix. dropFirst ( ) ) )
45
+ }
46
+ }
47
+
You can’t perform that action at this time.
0 commit comments