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.scala
70 lines (55 loc) · 1.68 KB
/
0211-design-add-and-search-words-data-structure.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import scala.collection.mutable.HashMap
class WordDictionary() {
val trie = new Trie()
def addWord(word: String) {
trie.insert(word)
}
def search(word: String): Boolean = {
trie.search(word)
}
}
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 = {
def helper(currNode: TrieNode, currCharIndex: Int): Boolean = {
if (currCharIndex == word.length) {
return currNode.isEndOfWord
}
val currChar = word(currCharIndex)
if (currChar == '.') {
var isFound = false
for ((_, childNode) <- currNode.children if !isFound) {
isFound = helper(childNode, currCharIndex + 1)
}
return isFound
} else {
if (currNode.children.contains(currChar)) {
return helper(currNode.children(currChar), currCharIndex + 1)
} else {
return false
}
}
}
helper(root, 0)
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* var obj = new WordDictionary()
* obj.addWord(word)
* var param_2 = obj.search(word)
*/