forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlledellebell.js
More file actions
67 lines (59 loc) ยท 1.74 KB
/
lledellebell.js
File metadata and controls
67 lines (59 loc) ยท 1.74 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
*
* @problem
* ๋ฌธ์์ด ๋ฐฐ์ด์ ๋จ์ผ ๋ฌธ์์ด๋ก ์ธ์ฝ๋ฉํ๊ณ ,
* ๋ค์ ์๋์ ๋ฌธ์์ด ๋ฐฐ์ด๋ก ๋์ฝ๋ฉํ๋ ๊ธฐ๋ฅ์ ๋ง๋ค์ด์ผ ํฉ๋๋ค.
*
* @example
* const encoded = encode(["hello", "world"]);
* console.log(encoded); // "5?hello5?world"
* const decoded = decode(encoded);
* console.log(decoded); // ["hello", "world"]
*
* @complexity
* - ์๊ฐ ๋ณต์ก๋:
* ใด encode: O(n) (n์ ๋ฌธ์์ด ๋ฐฐ์ด์ ์ด ๊ธธ์ด)
* ใด decode: O(n) (n์ ์ธ์ฝ๋ฉ๋ ๋ฌธ์์ด์ ๊ธธ์ด)
* - ๊ณต๊ฐ ๋ณต์ก๋:
* ใด encode: O(1) (์ถ๊ฐ ๋ฉ๋ชจ๋ฆฌ ์ฌ์ฉ ์์)
* ใด decode: O(1) (๊ฒฐ๊ณผ ๋ฐฐ์ด์ ์ ์ธํ ์ถ๊ฐ ๋ฉ๋ชจ๋ฆฌ ์ฌ์ฉ ์์)
*/
/**
* @param {string[]} strs - ์ธ์ฝ๋ฉํ ๋ฌธ์์ด ๋ฐฐ์ด
* @returns {string} - ์ธ์ฝ๋ฉ๋ ๋ฌธ์์ด
*/
const encode = (strs) => {
let encoded = '';
for (const str of strs) {
// ๋ฌธ์์ด์ "๊ธธ์ด?๋ฌธ์์ด" ํ์์ผ๋ก ์ถ๊ฐ
encoded += `${str.length}?${str}`;
}
return encoded;
};
/**
* @param {string} s - ์ธ์ฝ๋ฉ๋ ๋ฌธ์์ด
* @returns {string[]} - ๋์ฝ๋ฉ๋ ๋ฌธ์์ด ๋ฐฐ์ด
*/
const decode = (s) => {
const result = [];
let i = 0;
while (i < s.length) {
// ํ์ฌ ์์น์์ ์ซ์(๊ธธ์ด)๋ฅผ ์ฝ์
let length = 0;
while (s[i] !== '?') {
length = length * 10 + (s[i].charCodeAt(0) - '0'.charCodeAt(0)); // ์ซ์ ๊ณ์ฐ
i++;
}
// '?' ์ดํ์ ๋ฌธ์์ด์ ์ถ์ถ
i++; // '?'๋ฅผ ๊ฑด๋๋
const str = s.substring(i, i + length);
result.push(str);
// ๋ค์ ๋ฌธ์์ด๋ก ์ด๋
i += length;
}
return result;
};
const encoded = encode(["hello", "world"]);
console.log(encoded); // "5?hello5?world"
const decoded = decode(encoded);
console.log(decoded); // ["hello", "world"]