forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0211-design-add-and-search-words-data-structure.swift
61 lines (53 loc) · 1.51 KB
/
0211-design-add-and-search-words-data-structure.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
/**
* Question Link: https://leetcode.com/problems/design-add-and-search-words-data-structure/
*/
class TrieNode {
var children = [Character: TrieNode]()
var isWord = false
}
class WordDictionary {
let root: TrieNode
init() {
root = TrieNode()
}
func addWord(_ word: String) {
var curr: TrieNode? = root
for c in word {
if curr?.children[c] == nil {
curr?.children[c] = TrieNode()
}
curr = curr?.children[c]
}
curr?.isWord = true
}
func search(_ word: String) -> Bool {
var word = Array(word)
func dfs(j: Int, root: TrieNode) -> Bool {
var curr: TrieNode? = root
for i in j..<word.count {
var c = word[i]
if c == "." {
for child in curr!.children.values {
if dfs(j: i + 1, root: child) {
return true
}
}
return false
} else {
if curr?.children[c] == nil {
return false
}
curr = curr?.children[c]
}
}
return curr?.isWord == true
}
return dfs(j: 0, root: self.root)
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* let obj = WordDictionary()
* obj.addWord(word)
* let ret_2: Bool = obj.search(word)
*/