forked from tangweikun/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
53 lines (42 loc) · 951 Bytes
/
index.ts
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
// HELP:
function TrieNode(cur) {
return {
key: cur,
isWord: false,
children: {},
}
}
export const WordDictionary = function() {
this.root = new TrieNode()
}
WordDictionary.prototype.addWord = function(word) {
let node = this.root
for (let i = 0; i < word.length; i++) {
let cur = word[i]
if (!node.children[cur]) {
node.children[cur] = new TrieNode(cur)
}
node = node.children[cur]
}
node.isWord = true
}
WordDictionary.prototype.search = function(word) {
let node = this.root
function dfs(word, node, i) {
if (i === word.length) {
return node.isWord
}
let cur = word[i]
if (cur === '.') {
for (let key in node.children) {
if (dfs(word, node.children[key], i + 1)) {
return true
}
}
} else if (node.children[cur]) {
return dfs(word, node.children[cur], i + 1)
}
return false
}
return dfs(word, node, 0)
}