File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed
design-add-and-search-words-data-structure Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ class WordDictionary {
2
+ class TrieNode {
3
+ var children : [ Character : TrieNode ] = [ : ]
4
+ var isEndOfWord : Bool = false
5
+ }
6
+
7
+ private let root : TrieNode
8
+
9
+ init ( ) {
10
+ root = TrieNode ( )
11
+ }
12
+
13
+ func addWord( _ word: String ) {
14
+ let key = word. lowercased ( )
15
+ var current = root
16
+
17
+ for char in key {
18
+ if current. children [ char] == nil {
19
+ current. children [ char] = TrieNode ( )
20
+ }
21
+
22
+ if let node = current. children [ char] {
23
+ current = node
24
+ }
25
+ }
26
+
27
+ current. isEndOfWord = true
28
+ }
29
+
30
+ func search( _ word: String ) -> Bool {
31
+ let key = word. lowercased ( )
32
+ return searchInNode ( Array ( key) , 0 , root)
33
+ }
34
+
35
+ private func searchInNode( _ word: [ Character ] , _ index: Int , _ node: TrieNode ) -> Bool {
36
+ if index == word. count {
37
+ return node. isEndOfWord
38
+ }
39
+
40
+ let currentChar = word [ index]
41
+
42
+ if currentChar == " . " {
43
+ for (_, childNode) in node. children {
44
+ if searchInNode ( word, index + 1 , childNode) {
45
+ return true
46
+ }
47
+ }
48
+ return false
49
+ } else {
50
+ guard let nextNode = node. children [ currentChar] else {
51
+ return false
52
+ }
53
+
54
+ return searchInNode ( word, index + 1 , nextNode)
55
+ }
56
+ }
57
+ }
You can’t perform that action at this time.
0 commit comments