Skip to content

Commit 8a42f7d

Browse files
committed
3. Design Add and Search Words Data Structure
1 parent b8fa39b commit 8a42f7d

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
class WordDictionary {
2+
wordList: Set<string>;
3+
wordCountMap: Map<number, string[]>;
4+
constructor() {
5+
this.wordList = new Set();
6+
this.wordCountMap = new Map();
7+
}
8+
9+
// TC: O(1)
10+
// SC: O(n)
11+
addWord(word: string): void {
12+
this.wordList.add(word);
13+
const length = word.length;
14+
if (this.wordCountMap.has(length)) {
15+
this.wordCountMap.get(length).push(word);
16+
} else {
17+
this.wordCountMap.set(length, [word]);
18+
}
19+
return null;
20+
}
21+
22+
// TC: O(m*n) // m: words length, n: word length
23+
// SC: O(1)
24+
search(word: string): boolean {
25+
const len = word.length;
26+
const targetWord = word.replace(/\./g, "");
27+
const hasDot = len - targetWord.length !== 0;
28+
29+
if (!hasDot) return this.wordList.has(word);
30+
if (!this.wordCountMap.has(len)) {
31+
return false;
32+
}
33+
const words = this.wordCountMap.get(len);
34+
for (let i = 0; i < words.length; i++) {
35+
let match = true;
36+
for (let j = 0; j < words[i].length; j++) {
37+
if (word[j] !== "." && word[j] !== words[i][j]) {
38+
match = false;
39+
break;
40+
}
41+
}
42+
if (match) {
43+
return true;
44+
}
45+
}
46+
return false;
47+
}
48+
}

0 commit comments

Comments
 (0)