forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmmyeon.ts
More file actions
67 lines (61 loc) ยท 1.46 KB
/
mmyeon.ts
File metadata and controls
67 lines (61 loc) ยท 1.46 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
/*
* ์๊ฐ๋ณต์ก๋ : O(n)
* - ๋ฐฐ์ด 1ํ ์ํํ๋ฉด์ ๋ฌธ์์ด ํฉ์น๊ธฐ
*
* ๊ณต๊ฐ๋ณต์ก๋ : O(1)
*/
function encode(strs: string[]): string {
let result = strs[0];
for (let i = 1; i < strs.length; i++) {
result += "#" + strs[i];
}
return result;
}
/*
* ์๊ฐ๋ณต์ก๋ : O(n)
* - ๋ฌธ์ ์ํํ๋ฉด์ # ๊ธฐ์ค์ผ๋ก ๋๋
*
* ๊ณต๊ฐ๋ณต์ก๋ : O(n)
* - ๋ฌธ์์ด ๊ธธ์ด๋งํผ ์์ฑํด์ ๋ฆฌํด
*/
function decode(encoded: string): string[] {
return encoded.split("#");
}
// ์คํ ํ์ฉํ๋ ๋ฐฉ๋ฒ
/*
* ์๊ฐ๋ณต์ก๋ : O(n)
*
* ๊ณต๊ฐ๋ณต์ก๋ : O(1)
*/
// ["Hello","World"] => 5#Hello5#World
function encode(strs: string[]): string {
let result = "";
for (const str of strs) {
result += `${str.length}#${str}`;
}
return result;
}
/*
* ์ ๊ทผ ๋ฐฉ๋ฒ :
* - ๋ฐฐ์ด ๊ธธ์ด๋ฅผ ํฌํจํด์ encodeํ ๋ค decodeํ ๋ ๊ธธ์ด ํ์ฉํค์ stack์ ๋ด๋ ๋ฐฉ์
*
* ์๊ฐ๋ณต์ก๋ : O(n)
* - ์ธ์ฝ๋ฉ๋ ๋ฌธ์์ด 1ํ ์ํ
*
* ๊ณต๊ฐ๋ณต์ก๋ : O(n)
* - n์ result ๊ธธ์ด
*/
// 5#Hello5#World => ["Hello","World"]
function decode(encoded: string): string[] {
const result: string[] = [];
let index = 0;
while (index < encoded.length) {
const separatorIndex = encoded.indexOf("#", index);
const length = parseInt(encoded.slice(index, separatorIndex), 10);
index = separatorIndex + 1;
const str = encoded.slice(index, index + length);
result.push(str);
index += length;
}
return result;
}