Skip to content

Commit 8a9ba39

Browse files
committed
solve problem
1 parent b20c801 commit 8a9ba39

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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+

0 commit comments

Comments
 (0)