Untitled
unknown
javascript
a year ago
1.8 kB
8
Indexable
const EOS = '</EOS>';
var WordDictionary = function() {
this.words = new Set();
this.trie = new Map();
this.wordsToIndex = []; // this trick beats 99.73%
};
/**
* @param {string} word
* @return {void}
*/
WordDictionary.prototype.addWord = function(word) {
if (!this.words.has(word)) {
this.words.add(word);
this.wordsToIndex.push(word);
}
};
/**
* @param {string} word
* @return {void}
*/
WordDictionary.prototype.indexWord = function(word) {
let triePointer = this.trie;
for (const letter of word) {
if(!triePointer.has(letter)) {
triePointer.set(letter, new Map());
}
triePointer = triePointer.get(letter);
}
triePointer.set(EOS, null);
}
/**
* @param {string} word
* @return {boolean}
*/
WordDictionary.prototype.search = function(word) {
if (word.includes('.')) {
if (this.wordsToIndex.length > 0) {
this.wordsToIndex.forEach(w => {
this.indexWord(w);
});
this.wordsToIndex = [];
}
return trieSearch(this.trie, word, 0);
}
return this.words.has(word);
};
function trieSearch(root, word, index) {
if (root === null) {
return false;
}
if (word[index] === undefined) {
return root.has(EOS);
}
if (word[index] === '.') {
for (let [, nextRoot] of root.entries()) {
if (trieSearch(nextRoot, word, index+1)) {
return true;
}
}
return false;
}
if(!root.has(word[index])) {
return false;
}
return trieSearch(root.get(word[index]), word, index+1);
}
/**
* Your WordDictionary object will be instantiated and called as such:
* var obj = new WordDictionary()
* obj.addWord(word)
* var param_2 = obj.search(word)
*/
Editor is loading...
Leave a Comment