Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created August 5, 2020 07:46
Show Gist options
  • Save RP-3/615e4d364793792c8b23d6f1793bf377 to your computer and use it in GitHub Desktop.
Save RP-3/615e4d364793792c8b23d6f1793bf377 to your computer and use it in GitHub Desktop.
/**
* Initialize your data structure here.
*/
var WordDictionary = function() {
this.storage = new Array(26).fill(null);
};
/**
* Adds a word into the data structure.
* @param {string} word
* @return {void}
*/
WordDictionary.prototype.addWord = function(word) {
this._add(word, 0, this.storage);
};
WordDictionary.prototype._add = function(word, i, root) {
if(i >= word.length) return root.isTerminal = true;
const c = word.charCodeAt(i) - 97;
if(!root[c]) root[c] = new Array(26).fill(null);
this._add(word, i+1, root[c]);
};
/**
* 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}
*/
WordDictionary.prototype.search = function(word) {
return this._search(word, 0, this.storage);
};
WordDictionary.prototype._search = function(word, i, root){
if(i === word.length) return !!root.isTerminal;
if(word[i] === '.'){
// try all nodes in this root
for(let j=0; j<root.length; j++){
if(!root[j]) continue;
if(this._search(word, i+1, root[j])) return true;
}
return false;
}
const c = word.charCodeAt(i) - 97;
if(!root[c]) return false;
return this._search(word, i+1, root[c]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment