Skip to content

Commit 5a677bd

Browse files
committed
Encode and Decode Strings
1 parent 05a4fea commit 5a677bd

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
*
3+
* @problem
4+
* ๋ฌธ์ž์—ด ๋ฐฐ์—ด์„ ๋‹จ์ผ ๋ฌธ์ž์—ด๋กœ ์ธ์ฝ”๋”ฉํ•˜๊ณ ,
5+
* ๋‹ค์‹œ ์›๋ž˜์˜ ๋ฌธ์ž์—ด ๋ฐฐ์—ด๋กœ ๋””์ฝ”๋”ฉํ•˜๋Š” ๊ธฐ๋Šฅ์„ ๋งŒ๋“ค์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
6+
*
7+
* @example
8+
* const encoded = encode(["hello", "world"]);
9+
* console.log(encoded); // "5?hello5?world"
10+
* const decoded = decode(encoded);
11+
* console.log(decoded); // ["hello", "world"]
12+
*
13+
* @description
14+
* - ์‹œ๊ฐ„ ๋ณต์žก๋„:
15+
* ใ„ด encode: O(n) (n์€ ๋ฌธ์ž์—ด ๋ฐฐ์—ด์˜ ์ด ๊ธธ์ด)
16+
* ใ„ด decode: O(n) (n์€ ์ธ์ฝ”๋”ฉ๋œ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด)
17+
* - ๊ณต๊ฐ„ ๋ณต์žก๋„:
18+
* ใ„ด encode: O(1) (์ถ”๊ฐ€ ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ ์—†์Œ)
19+
* ใ„ด decode: O(1) (๊ฒฐ๊ณผ ๋ฐฐ์—ด์„ ์ œ์™ธํ•œ ์ถ”๊ฐ€ ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ ์—†์Œ)
20+
*/
21+
22+
/**
23+
* @param {string[]} strs - ์ธ์ฝ”๋”ฉํ•  ๋ฌธ์ž์—ด ๋ฐฐ์—ด
24+
* @returns {string} - ์ธ์ฝ”๋”ฉ๋œ ๋ฌธ์ž์—ด
25+
*/
26+
const encode = (strs) => {
27+
let encoded = '';
28+
for (const str of strs) {
29+
// ๋ฌธ์ž์—ด์„ "๊ธธ์ด?๋ฌธ์ž์—ด" ํ˜•์‹์œผ๋กœ ์ถ”๊ฐ€
30+
encoded += `${str.length}?${str}`;
31+
}
32+
return encoded;
33+
};
34+
35+
/**
36+
* @param {string} s - ์ธ์ฝ”๋”ฉ๋œ ๋ฌธ์ž์—ด
37+
* @returns {string[]} - ๋””์ฝ”๋”ฉ๋œ ๋ฌธ์ž์—ด ๋ฐฐ์—ด
38+
*/
39+
const decode = (s) => {
40+
const result = [];
41+
let i = 0;
42+
43+
while (i < s.length) {
44+
// ํ˜„์žฌ ์œ„์น˜์—์„œ ์ˆซ์ž(๊ธธ์ด)๋ฅผ ์ฝ์Œ
45+
let length = 0;
46+
while (s[i] !== '?') {
47+
length = length * 10 + (s[i].charCodeAt(0) - '0'.charCodeAt(0)); // ์ˆซ์ž ๊ณ„์‚ฐ
48+
i++;
49+
}
50+
51+
// '?' ์ดํ›„์˜ ๋ฌธ์ž์—ด์„ ์ถ”์ถœ
52+
i++; // '?'๋ฅผ ๊ฑด๋„ˆ๋œ€
53+
const str = s.substring(i, i + length);
54+
result.push(str);
55+
56+
// ๋‹ค์Œ ๋ฌธ์ž์—ด๋กœ ์ด๋™
57+
i += length;
58+
}
59+
60+
return result;
61+
};
62+
63+
const encoded = encode(["hello", "world"]);
64+
console.log(encoded); // "5?hello5?world"
65+
66+
const decoded = decode(encoded);
67+
console.log(decoded); // ["hello", "world"]

0 commit comments

Comments
ย (0)