Skip to content

Commit e2399e0

Browse files
committed
Add solution #208
1 parent 71a8583 commit e2399e0

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,7 @@
187187
205|[Isomorphic Strings](./0205-isomorphic-strings.js)|Easy|
188188
206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy|
189189
207|[Course Schedule](./0207-course-schedule.js)|Medium|
190+
208|[Implement Trie (Prefix Tree)](./0208-implement-trie-prefix-tree.js)|Medium|
190191
209|[Minimum Size Subarray Sum](./0209-minimum-size-subarray-sum.js)|Medium|
191192
211|[Design Add and Search Words Data Structure](./0211-design-add-and-search-words-data-structure.js)|Medium|
192193
213|[House Robber II](./0213-house-robber-ii.js)|Medium|
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/**
2+
* 208. Implement Trie (Prefix Tree)
3+
* https://leetcode.com/problems/implement-trie-prefix-tree/
4+
* Difficulty: Medium
5+
*
6+
* A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store
7+
* and retrieve keys in a dataset of strings. There are various applications of this data structure,
8+
* such as autocomplete and spellchecker.
9+
*
10+
* Implement the Trie class:
11+
* - Trie() Initializes the trie object.
12+
* - void insert(String word) Inserts the string word into the trie.
13+
* - boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted
14+
* before), and false otherwise.
15+
* - boolean startsWith(String prefix) Returns true if there is a previously inserted string word
16+
* that has the prefix prefix, and false otherwise.
17+
*/
18+
19+
var Trie = function() {
20+
this.root = {};
21+
};
22+
23+
/**
24+
* @param {string} word
25+
* @return {void}
26+
*/
27+
Trie.prototype.insert = function(word) {
28+
let node = this.root;
29+
for (const char of word) {
30+
if (!node[char]) {
31+
node[char] = {};
32+
}
33+
node = node[char];
34+
}
35+
node.isWord = true;
36+
};
37+
38+
/**
39+
* @param {string} word
40+
* @return {boolean}
41+
*/
42+
Trie.prototype.search = function(word) {
43+
const node = this.find(word);
44+
return node != null && node.isWord === true;
45+
};
46+
47+
/**
48+
* @param {string} prefix
49+
* @return {boolean}
50+
*/
51+
Trie.prototype.startsWith = function(prefix) {
52+
return this.find(prefix) !== null;
53+
};
54+
55+
/**
56+
* @param {string} word
57+
* @return {boolean}
58+
*/
59+
Trie.prototype.find = function(word) {
60+
let node = this.root;
61+
for (const char of word) {
62+
node = node[char];
63+
if (!node) {
64+
return null;
65+
}
66+
}
67+
return node;
68+
};

0 commit comments

Comments
 (0)