Skip to content

Commit 1fcf5fe

Browse files
committed
Add solution #211
1 parent 8726bce commit 1fcf5fe

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,7 @@
184184
205|[Isomorphic Strings](./0205-isomorphic-strings.js)|Easy|
185185
206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy|
186186
207|[Course Schedule](./0207-course-schedule.js)|Medium|
187+
211|[Design Add and Search Words Data Structure](./0211-design-add-and-search-words-data-structure.js)|Medium|
187188
213|[House Robber II](./0213-house-robber-ii.js)|Medium|
188189
214|[Shortest Palindrome](./0214-shortest-palindrome.js)|Hard|
189190
215|[Kth Largest Element in an Array](./0215-kth-largest-element-in-an-array.js)|Medium|
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/**
2+
* 211. Design Add and Search Words Data Structure
3+
* https://leetcode.com/problems/design-add-and-search-words-data-structure/
4+
* Difficulty: Medium
5+
*
6+
* Design a data structure that supports adding new words and finding if a string matches
7+
* any previously added string.
8+
*
9+
* Implement the WordDictionary class:
10+
* - WordDictionary() Initializes the object.
11+
* - void addWord(word) Adds word to the data structure, it can be matched later.
12+
* - bool search(word) Returns true if there is any string in the data structure that
13+
* matches word or false otherwise. word may contain dots '.' where dots can be
14+
* matched with any letter.
15+
*/
16+
17+
18+
var WordDictionary = function() {
19+
this.root = {};
20+
};
21+
22+
/**
23+
* @param {string} word
24+
* @return {void}
25+
*/
26+
WordDictionary.prototype.addWord = function(word) {
27+
let node = this.root;
28+
29+
for (const character of word) {
30+
node[character] = node[character] || {};
31+
node = node[character];
32+
}
33+
34+
node.isTail = true;
35+
};
36+
37+
/**
38+
* @param {string} word
39+
* @return {boolean}
40+
*/
41+
WordDictionary.prototype.search = function(word) {
42+
return dfs(this.root, 0);
43+
44+
function dfs(node, i) {
45+
if (word.length === i) {
46+
return node.isTail;
47+
}
48+
if (word[i] === '.') {
49+
for (const key in node) {
50+
if (dfs(node[key], i + 1)) {
51+
return true;
52+
}
53+
}
54+
} else if (node[word[i]] && dfs(node[word[i]], i + 1)) {
55+
return true;
56+
}
57+
58+
return false;
59+
}
60+
};

0 commit comments

Comments
 (0)