-
Notifications
You must be signed in to change notification settings - Fork 889
/
WordDictionary.swift
79 lines (62 loc) · 1.49 KB
/
WordDictionary.swift
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
/**
* Question Link: https://leetcode.com/problems/add-and-search-word-data-structure-design/
* Primary idea: Trie with DFS to resolve search problem
*
* Time Complexity: O(n), Space Complexity: O(n)
*
*/
class WordDictionary {
var trie = Trie()
func add(word: String) {
trie.add(word: word)
}
func search(word: String) -> Bool {
return trie.search(word:word)
}
}
class TrieNode {
var children: [Character: TrieNode]
var isEnd: Bool
init() {
self.children = [Character: TrieNode]()
self.isEnd = false
}
}
class Trie {
var root: TrieNode
init() {
root = TrieNode()
}
func add(word: String) {
var node = root
for char in word {
if node.children[char] == nil {
node.children[char] = TrieNode()
}
node = node.children[char]!
}
node.isEnd = true
}
func search(word:String) -> Bool {
return dfsSearch(word: word, index: 0, node: root)
}
fileprivate func dfsSearch(word: String, index: Int, node: TrieNode) -> Bool {
if index == word.count {
return node.isEnd
}
let char = Array(word)[index]
if char != "." {
guard let nextNode = node.children[char] else {
return false
}
return dfsSearch(word: word, index: index + 1, node: nextNode)
} else{
for key in node.children.keys {
if dfsSearch(word: word, index: index + 1, node: node.children[key]!) {
return true
}
}
return false
}
}
}