const WordDictionary = function () {
this.words = {};
}
// WordDictionary.prototype.addWord = (word) => {
// const that = this;
// if (!word) {
// return false;
// }
// if (that.words && that.words[word.length]) {
// that.words[word.length].push(word);
// } else {
// console.log('====', that.words);
// that.words[word.length] = [word];
// }
// }
WordDictionary.prototype.addWord = function (word) {
// 若该字符串对应长度的数组已经存在,则只做添加
console.log(this.words);
if (this.words[word.length]) {
this.words[word.length].push(word)
} else {
// 若该字符串对应长度的数组还不存在,则先创建
this.words[word.length] = [word]
}
};
WordDictionary.prototype.searchWord = (word) => {
if (!this.words[word.length]) {
return false;
}
if (!word.includes('.')) {
return this.words[word.length].includes(word);
}
const reg = new RegExp(word);
return this.words[word.length].some((i) => {
return reg.test(i);
})
}
// WordDictionary.prototype.addWord('231');
WordDictionary.prototype.addWord('6783');
console.log(WordDictionary.prototype.words)
console