-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path압축.js
35 lines (32 loc) · 829 Bytes
/
압축.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const initDictionary = (dict) => {
for (let i = "A".charCodeAt(0); i <= "Z".charCodeAt(0); i++) {
dict.set(String.fromCharCode(i), dict.size + 1);
}
};
const findLongestMsg = (msg, dict) => {
let longestMsg = "";
for (const alpha of msg) {
if (!dict.has(longestMsg + alpha)) {
break;
}
longestMsg += alpha;
}
return longestMsg;
};
const enrollNewWord = (word, dict) => {
dict.set(word, dict.size + 1);
};
function solution(msg) {
const answer = [];
const dict = new Map();
initDictionary(dict);
while (!!msg.length) {
const longestMsg = findLongestMsg(msg, dict);
answer.push(dict.get(longestMsg));
if (longestMsg.length < msg.length) {
enrollNewWord(longestMsg + msg[longestMsg.length], dict);
}
msg = msg.slice(longestMsg.length);
}
return answer;
}