Skip to content

Commit 4d408de

Browse files
committed
add: DaleStudy#257 Design Add And Search Words Data Structure
1 parent ab5ae5a commit 4d408de

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
// 1번풀이 O(n × m)
2+
class WordDictionary1 {
3+
private words: string[];
4+
constructor() {
5+
this.words = [];
6+
}
7+
8+
addWord(word: string): void {
9+
this.words.push(word);
10+
}
11+
search(word: string): boolean {
12+
return this.words
13+
.filter((savedWord) => savedWord.length === word.length)
14+
.some((savedWord) => {
15+
for (let i = 0; i < word.length; i++) {
16+
if (word[i] === ".") continue;
17+
if (word[i] !== savedWord[i]) return false;
18+
}
19+
return true;
20+
});
21+
}
22+
};
23+
24+
// 2번풀이 : Trie(트라이) 자료구조
25+
type TrieNode = {
26+
children: { [key: string]: TrieNode };
27+
isEnd: boolean;
28+
};
29+
30+
class WordDictionary {
31+
private root: TrieNode;
32+
constructor() {
33+
this.root = {
34+
children: {},
35+
isEnd: false,
36+
};
37+
}
38+
addWord(word: string): void {
39+
let node = this.root;
40+
41+
for (let i = 0; i < word.length; i++) {
42+
const char = word[i];
43+
44+
if (!node.children[char]) {
45+
node.children[char] = {
46+
children: {},
47+
isEnd: false,
48+
};
49+
}
50+
51+
node = node.children[char];
52+
}
53+
54+
node.isEnd = true;
55+
}
56+
search(word: string): boolean {
57+
const dfs = (node: TrieNode, index: number): boolean => {
58+
if (index === word.length) return node.isEnd;
59+
60+
const char = word[index];
61+
62+
if (char === ".") {
63+
for (const nextChar in node.children) {
64+
if (dfs(node.children[nextChar], index + 1)) {
65+
return true;
66+
}
67+
}
68+
return false;
69+
}
70+
71+
if (!node.children[char]) return false;
72+
return dfs(node.children[char], index + 1);
73+
};
74+
75+
return dfs(this.root, 0);
76+
}
77+
};

0 commit comments

Comments
 (0)