-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathadd-and-search-word-data-structure-design.js
69 lines (64 loc) · 1.67 KB
/
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
/**
* @constructor
*/
var WordDictionary = function () {
this.root = new TrieNode('root');
};
var TrieNode = function (key) {
return {
key: key,
isWord: false
}
}
/**
* @param {string} word
* @return {void}
* Adds a word into the data structure.
*/
WordDictionary.prototype.addWord = function (word) {
var tree = this.root;
for (var i = 0; i < word.length; i++) {
if (!tree[word[i]]) {
tree[word[i]] = new TrieNode(word[i]);
}
tree = tree[word[i]];
}
tree.isWord = true;
};
/**
* @param {string} word
* @return {boolean}
* Returns if the word is in the data structure. A word could
* contain the dot character '.' to represent any one letter.
*/
WordDictionary.prototype.search = function (word) {
return searchBuilder(word, this.root);
function searchBuilder(word, tree) {
if (word === "" && tree.isWord) {
return true;
}
if (word[0] !== '.') {
if (!tree[word[0]]) {
return false;
} else {
return searchBuilder(word.substring(1, word.length), tree[word[0]]);
}
} else {
for (var i in tree) {
if (i === 'key' || i === 'isWord') {
continue;
}
if (searchBuilder(word.substring(1, word.length), tree[i])) {
return true;
}
}
return false;
}
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* var wordDictionary = new WordDictionary();
* wordDictionary.addWord("word");
* wordDictionary.search("pattern");
*/