Skip to content

Commit ef1712e

Browse files
committed
solve problem
1 parent 85295ba commit ef1712e

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
class WordDictionary {
2+
3+
class TrieNode {
4+
var children: [Character: TrieNode] = [:]
5+
var isEndOfWord: Bool = false
6+
}
7+
8+
var root: TrieNode?
9+
10+
init() {
11+
root = TrieNode()
12+
}
13+
14+
func addWord(_ word: String) {
15+
var currentNode = root
16+
for (index, char) in word.enumerated() {
17+
if currentNode?.children[char] == nil {
18+
currentNode?.children[char] = TrieNode()
19+
}
20+
currentNode = currentNode?.children[char]
21+
if index == word.count - 1 {
22+
currentNode?.isEndOfWord = true
23+
}
24+
}
25+
}
26+
27+
func search(_ word: String) -> Bool {
28+
return dfs(root, word: word, index: 0)
29+
}
30+
31+
func dfs(_ node: TrieNode?, word: String, index: Int) -> Bool {
32+
guard let currentNode = node else {
33+
return false
34+
}
35+
if index == word.count {
36+
return currentNode.isEndOfWord
37+
}
38+
39+
let char = Array(word)[index]
40+
if char == "." {
41+
for child in currentNode.children.values {
42+
let result = dfs(child, word: word, index: index + 1)
43+
if result {
44+
return true
45+
}
46+
}
47+
} else {
48+
if let child = currentNode.children[char] {
49+
return dfs(child, word: word, index: index + 1)
50+
} else {
51+
return false
52+
}
53+
}
54+
55+
return false
56+
}
57+
}
58+

0 commit comments

Comments
 (0)