Skip to content

Commit 2788e0c

Browse files
committed
[WEEK 05] encode and decode strings
1 parent caac245 commit 2788e0c

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
public class Solution {
2+
/*
3+
* @param strs: a list of strings
4+
* @return: encodes a list of strings to a single string.
5+
*/
6+
public String encode(List<String> strs) {
7+
StringBuilder sb = new StringBuilder();
8+
for (String s : strs) {
9+
sb.append(s.length());
10+
sb.append('#');
11+
sb.append(s);
12+
}
13+
return sb.toString();
14+
}
15+
16+
/*
17+
* @param str: A string
18+
* @return: decodes a single string to a list of strings
19+
*/
20+
public List<String> decode(String str) {
21+
List<String> res = new ArrayList<>();
22+
int i = 0;
23+
while (i < str.length()) {
24+
// '#' 앞의 숫자를 길이로 파싱
25+
int len = 0;
26+
while (str.charAt(i) != '#') {
27+
len = len * 10 + (str.charAt(i) - '0');
28+
i++;
29+
}
30+
i++; // '#' 건너뛰기
31+
32+
// 정확히 len 글자만 잘라내기
33+
res.add(str.substring(i, i + len));
34+
i += len;
35+
}
36+
return res;
37+
}
38+
}

0 commit comments

Comments
 (0)