-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path211.添加与搜索单词-数据结构设计.ts
75 lines (65 loc) · 1.66 KB
/
211.添加与搜索单词-数据结构设计.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
* @lc app=leetcode.cn id=211 lang=typescript
*
* [211] 添加与搜索单词 - 数据结构设计
*/
// @lc code=start
class Tree {
children: Array<Tree>;
isWord: boolean;
constructor(children = [], isWord = false) {
this.children = children;
this.isWord = isWord;
}
}
class WordDictionary {
root: Tree;
constructor() {
this.root = new Tree();
}
addWord(word: string): void {
const len = word.length;
let root = this.root;
for (let i = 0; i < len; i++) {
const j = word.charCodeAt(i);
root.children[j] ??= new Tree([], i === len - 1);
root.children[j].isWord ||= i === len - 1;
root = root.children[j];
}
}
search(word: string): boolean {
const len = word.length;
const stack: Array<Tree & { index: number }> = [{ ...this.root, index: 0 }];
while (stack.length) {
const { children = [], isWord, index } = stack.pop();
if (index === len && isWord) {
return true;
}
if (index === len) {
continue;
}
const j = word.charCodeAt(index);
if (j < 97) {
stack.push(...children.filter(Boolean).map((i) => ({ ...i, index: index + 1 })));
} else {
if (children[j]) {
stack.push({ ...children[j], index: index + 1 });
}
}
}
return false;
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* var obj = new WordDictionary()
* obj.addWord(word)
* var param_2 = obj.search(word)
*/
/**
* Your WordDictionary object will be instantiated and called as such:
* var obj = new WordDictionary()
* obj.addWord(word)
* var param_2 = obj.search(word)
*/
// @lc code=end