Skip to content

Commit c09dd4d

Browse files
feat: encode-and-decode-strings 풀이
1 parent 6ecfde0 commit c09dd4d

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// 네트워크 전송을 위해서 문자열 리스트를 하나의 문자열로 안전하게 합치고
2+
// 다시 분리하는 함수를 작성하세요.
3+
4+
/**
5+
풀이 과정:
6+
구분자를 "a,b,c"와 같이 ,로 join하면, 원래 문자열에 ,가 포함될 때 깨진다.
7+
따라서 길이 정보를 함께 저장하거나 특수 escape 문자를 써야한다.
8+
9+
10+
*/
11+
/**
12+
* Encodes a list of strings to a single string.
13+
* @param {string[]} strs
14+
* @return {string}
15+
*/
16+
function encode(strs) {
17+
// 각 문자열 앞에 "길이#"를 붙임
18+
// 예: ["abc", "de"] -> "3#abc2#de"
19+
return strs.map((s) => `${s.length}#${s}`).join("");
20+
}
21+
22+
/**
23+
* Decodes a single string to a list of strings.
24+
* @param {string} s
25+
* @return {string[]}
26+
*/
27+
function decode(s) {
28+
let res = [];
29+
let i = 0;
30+
31+
while (i < s.length) {
32+
// 1. 길이 읽기
33+
let j = i;
34+
while (s[j] !== "#") j++;
35+
let length = parseInt(s.slice(i, j), 10);
36+
37+
// 2. 길이에 맞춰 문자열 추출
38+
let str = s.slice(j + 1, j + 1 + length);
39+
res.push(str);
40+
41+
// 3. 인덱스 이동
42+
i = j + 1 + length;
43+
}
44+
45+
return res;
46+
}

0 commit comments

Comments
 (0)