Skip to content

Commit 7bdb519

Browse files
committed
Feat: 트라이_접두사 찾기(실버1)
1 parent 1aabc2d commit 7bdb519

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
// trie로 N개의 문자를 기록해두고
2+
// M개의 문자가 이에 포함되는지 확인한다.
3+
const array = [
4+
"5",
5+
"10",
6+
"baekjoononlinejudge",
7+
"startlink",
8+
"codeplus",
9+
"sundaycoding",
10+
"codingsh",
11+
"baekjoon",
12+
"star",
13+
"start",
14+
"code",
15+
"sunday",
16+
"coding",
17+
"cod",
18+
"online",
19+
"judge",
20+
"plus",
21+
];
22+
23+
const countN = Number(array[0]);
24+
const countM = Number(array[1]);
25+
26+
const N = array.slice(2, 2 + countN);
27+
const M = array.slice(2 + countN, 2 + countN + countM);
28+
console.log(N, M);
29+
30+
// tire 문자열 삽입
31+
// 1. 루트는 비어있다.
32+
// 2. 문자가 존재하는지 확인 후 없으면 추가 후 이동
33+
class Node {
34+
constructor(value = "") {
35+
this.value = value;
36+
this.children = new Map();
37+
}
38+
}
39+
40+
let count = 0;
41+
42+
class Trie {
43+
constructor() {
44+
this.root = new Node();
45+
}
46+
47+
insert(string) {
48+
let currentNode = this.root;
49+
50+
for (const char of string) {
51+
if (!currentNode.children.has(char)) {
52+
currentNode.children.set(char, new Node(currentNode.value + char));
53+
}
54+
55+
currentNode = currentNode.children.get(char);
56+
}
57+
}
58+
59+
has(string) {
60+
let currentNode = this.root;
61+
62+
for (const char of string) {
63+
if (!currentNode.children.has(char)) {
64+
return false;
65+
}
66+
currentNode = currentNode.children.get(char);
67+
}
68+
69+
return true;
70+
}
71+
}
72+
73+
const trie = new Trie();
74+
for (const i in N) {
75+
trie.insert(N[i]);
76+
}
77+
78+
for (const i in M) {
79+
if (trie.has(M[i]) === true) {
80+
count += 1;
81+
}
82+
}
83+
84+
console.log(count);

0 commit comments

Comments
 (0)