Design Add and Search Words Data Structure LeetCode solution in JavaScript

1
var WordDictionary = function () {
2
this.aryWordList = [];
3
};
4

5
/**
6
* @param {string} word
7
* @return {void}
8
*/
9
WordDictionary.prototype.addWord = function (word) {
10
this.aryWordList.push(word);
11
};
12

13
/**
14
* @param {string} word
15
* @return {boolean}
16
*/
17
WordDictionary.prototype.search = function (word) {
18
const isWordsMatch = (first, second) => {
19
if (first.length !== second.length) return false;
20

21
if (first.length == 0 && second.length == 0) return true; // Exit case for recursion
22

23
if (first[0] === second[0] || first[0] === "." || second[0] === ".")
24
return isWordsMatch(first.substring(1), second.substring(1));
25

26
return false;
27
};
28

29
const isWordFound = () => {
30
let isFound = false;
31
for (var indexI = 0; indexI < this.aryWordList.length; indexI++) {
32
if (isWordsMatch(this.aryWordList[indexI], word)) {
33
isFound = true;
34
break;
35
}
36
}
37

38
return isFound;
39
};
40

41
return word.indexOf(".") === -1
42
? this.aryWordList.includes(word)
43
: isWordFound();
44
};
45

46
/**
47
* Your WordDictionary object will be instantiated and called as such:
48
* var obj = new WordDictionary()
49
* obj.addWord(word)
50
* var param_2 = obj.search(word)
51
*/

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0