|
| 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