forked from gbrigens/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImplementTrie.swift
57 lines (52 loc) · 1.56 KB
/
ImplementTrie.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
/**
* Question Link: https://leetcode.com/problems/implement-trie-prefix-tree/
* Primary idea: implement a tree data structure where each node has a dictionary storing
* all descendants having a common prefix.
*
* Time Complexity: O(m) where m is the length of a target string
* Space Complexity: insert - O(m), search - O(1), startsWith - O(1)
*
*/
class Trie {
private var nodes: [Character: Trie]
/** Initialize your data structure here. */
init() {
nodes = [:]
}
/** Inserts a word into the trie. */
func insert(_ word: String) {
var trie = self
word.forEach {
if let subTrie = trie.nodes[$0] {
trie = subTrie
} else {
let subTrie = Trie()
trie.nodes[$0] = subTrie
trie = subTrie
}
}
trie.nodes["#"] = Trie()
}
/** Returns if the word is in the trie. */
func search(_ word: String) -> Bool {
var trie = self
for char in word {
guard let subTrie = trie.nodes[char] else {
return false
}
trie = subTrie
}
return trie.nodes["#"] != nil;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
func startsWith(_ prefix: String) -> Bool {
var trie = self
for char in prefix {
guard let subTrie = trie.nodes[char] else {
return false
}
trie = subTrie
}
return true
}
}