Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 37ed60f

Browse files
feat: add typescript solution to lc problem: No.0208.Implement Trie (Prefix Tree)
1 parent 5322f72 commit 37ed60f

File tree

1 file changed

+46
-0
lines changed
  • solution/0200-0299/0208.Implement Trie (Prefix Tree)

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class TrieNode {
2+
children;
3+
isEnd;
4+
constructor() {
5+
this.children = new Array(26);
6+
this.isEnd = false;
7+
}
8+
}
9+
10+
class Trie {
11+
root;
12+
constructor() {
13+
this.root = new TrieNode();
14+
}
15+
16+
insert(word: string): void {
17+
let head = this.root;
18+
for (let char of word) {
19+
let index = char.charCodeAt(0) - 97;
20+
if (!head.children[index]) {
21+
head.children[index] = new TrieNode();
22+
}
23+
head = head.children[index];
24+
}
25+
head.isEnd = true;
26+
}
27+
28+
search(word: string): boolean {
29+
let head = this.searchPrefix(word);
30+
return head != null && head.isEnd;
31+
}
32+
33+
startsWith(prefix: string): boolean {
34+
return this.searchPrefix(prefix) != null;
35+
}
36+
37+
private searchPrefix(prefix: string) {
38+
let head = this.root;
39+
for (let char of prefix) {
40+
let index = char.charCodeAt(0) - 97;
41+
if (!head.children[index]) return null;
42+
head = head.children[index];
43+
}
44+
return head;
45+
}
46+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /