-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path211. Add and Search Word - Data structure design.js
83 lines (73 loc) · 1.97 KB
/
211. Add and Search Word - Data structure design.js
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
76
77
78
79
80
81
82
83
/**
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing only
letters a-z or .. A . means it can represent any one letter.
*/
/**
* Data Structure: Trie Tree
* addWord - O(m) - m is the length of the new word
* search - O(n) - n is the total number of characters in all words
*/
class TrieNode {
constructor() {
this.isWord = false;
this.children = {}; //(char, TrieNode)
}
}
class WordDictionary {
constructor() {
this.root = new TrieNode();
}
/**
* Adds a word into the data structure.
* @param {string} word
* @return {void}
*/
addWord(word) {
let node = this.root;
for (const char of word) {
if (!node.children[char]) {
node.children[char] = new TrieNode();
}
node = node.children[char];
}
node.isWord = true;
}
/**
* Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
* @param {string} word
* @return {boolean}
*/
search(word) {
const stack = [{ i: 0, node: this.root }];
while (stack.length) {
const { i, node } = stack.pop();
if (i === word.length) {
if (node.isWord) return true;
continue;
}
const char = word[i];
if (char === '.') {
if (!node.children) continue;
for (const c in node.children) {
const sub = node.children[c];
stack.push({ i: i + 1, node: sub });
}
} else {
if (!node.children[char]) continue;
stack.push({ i: i + 1, node: node.children[char] });
}
}
return false;
}
}
let dict = new WordDictionary();
dict.addWord("bad");
dict.addWord("dad");
dict.addWord("mad");
console.log(dict.search("pad")); // false
console.log(dict.search("bad")); // true
console.log(dict.search(".ad")); // true
console.log(dict.search("b..")); // true