Skip to content

Commit 23d1e0f

Browse files
committed
feat: encode and decode strings
1 parent a7fec99 commit 23d1e0f

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

encode-and-decode-strings/anniemon.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
/**
3+
* 시간 복잡도: strs의 길이만큼 순회하므로, O(n)
4+
* 공간 복잡도: 결괏값 제외 추가 변수 사용 없으므로 O(1)
5+
*/
6+
/**
7+
* @param {string[]} strs
8+
* @returns {string}
9+
*/
10+
encode(strs) {
11+
return strs.reduce((acc, cur) => acc+ `${cur.length}` + '!' + cur, '');
12+
}
13+
14+
/**
15+
* 시간 복잡도: str의 길이만큼 순회하므로 str의 길이가 m이면, O(m)
16+
* 공간 복잡도: 결괏값 제외 상수 크기 변수만 사용하므로, O(1)
17+
*/
18+
/**
19+
* @param {string} str
20+
* @returns {string[]}
21+
*/
22+
decode(str) {
23+
const res = [];
24+
let i = 0;
25+
while (i < str.length) {
26+
let j = i;
27+
while (str[j] !== '!') {
28+
j++;
29+
}
30+
const len = Number(str.slice(i, j));
31+
const s = str.slice(j + 1, j + 1 + len);
32+
res.push(s);
33+
i = j + 1 + len;
34+
}
35+
return res;
36+
}
37+
}

0 commit comments

Comments
 (0)