forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0208-implement-trie-prefix-tree.scala
55 lines (45 loc) · 1.26 KB
/
0208-implement-trie-prefix-tree.scala
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
import scala.collection.mutable.HashMap
class Trie() {
class TrieNode {
val children: HashMap[Char, TrieNode] = HashMap()
var isEndOfWord = false
}
private var root: TrieNode = new TrieNode()
def insert(word: String): Unit = {
var curr = root
word.foreach(c => {
if (!curr.children.contains(c)) {
curr.children(c) = new TrieNode()
}
curr = curr.children(c)
})
curr.isEndOfWord = true
}
def search(word: String): Boolean = {
traverse(word) match {
case Some(endNode) => endNode.isEndOfWord
case None => false
}
}
def startsWith(prefix: String): Boolean = {
traverse(prefix).isDefined
}
private def traverse(word: String): Option[TrieNode] = {
var curr = root
for (c <- word) {
if (!curr.children.contains(c)) {
return None
} else {
curr = curr.children(c)
}
}
return Some(curr)
}
}
/**
* Your Trie object will be instantiated and called as such:
* var obj = new Trie()
* obj.insert(word)
* var param_2 = obj.search(word)
* var param_3 = obj.startsWith(prefix)
*/