forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTessa1217.java
More file actions
39 lines (33 loc) ยท 1.2 KB
/
Tessa1217.java
File metadata and controls
39 lines (33 loc) ยท 1.2 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
/**
* ๋ฌธ์์ด์ ๋ํ encode, decode ์๊ณ ๋ฆฌ์ฆ ๋์์ธ
* ๋ฌธ์์ด์ ASCII 256 ๋ชจ๋ ํฌํจ ๊ฐ๋ฅ (๋ฌธ์๋ง ํฌํจํ ๊ฒ ์๋๋ฏ๋ก ํน์๋ฌธ์(:, ?) ๋ฑ๋ ์๊ณ ๋ฆฌ์ฆ ๋ด์์ ๊ณ ๋ คํด์ผ ํจ
* */
import java.util.ArrayList;
import java.util.List;
public class Solution {
public static String encode(List<String> strs) {
StringBuilder sb = new StringBuilder();
for (String str : strs) {
// : ๊ตฌ๋ถ์ ์์ ๋จ์ด์ ๊ธธ์ด ์ถ๊ฐ
sb.append(str.length()).append(":").append(str);
}
return sb.toString();
}
public static List<String> decode(String str) {
List<String> words = new ArrayList<>();
int i = 0;
while (i < str.length()) {
// ๊ตฌ๋ถ์ ๊ธฐ์ค ์ธ๋ฑ์ค
int colonIdx = str.indexOf(':', i);
// ๋จ์ด์ ๊ธธ์ด ์ธ๋ฑ์ค
int length = Integer.parseInt(str.substring(i, colonIdx));
// ๋จ์ด ์์
int wordStart = colonIdx + 1;
// ๋จ์ด์ ๋
int wordEnd = wordStart + length;
words.add(str.substring(wordStart, wordEnd));
i = wordEnd;
}
return words;
}
}