Skip to content

Commit 933b354

Browse files
encode and decode strings solution
1 parent 0fe2d97 commit 933b354

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
4+
class SolutionEncodeAndDecodeStrings {
5+
private static final char SEPERATOR = '/';
6+
/*
7+
* @param strs: a list of strings
8+
* @return: encodes a list of strings to a single string.
9+
*/
10+
// 풀이: 문자열 길이를 구분자와 함께 encode해 decode시 문자열 길이를 참고할 수 있도록 한다
11+
// 시간복잡도: O(N), 공간복잡도: O(1)
12+
public String encode(List<String> strs) {
13+
// write your code here
14+
var answer = new StringBuilder();
15+
16+
for (var str : strs) {
17+
answer.append(str.length())
18+
.append(str)
19+
.append(SEPERATOR);
20+
}
21+
22+
return answer.toString();
23+
}
24+
25+
/*
26+
* @param str: A string
27+
* @return: decodes a single string to a list of strings
28+
*/
29+
// 풀이: 문자열 길이를 구분자와 함께 encode해 decode시 문자열 길이를 참고할 수 있도록 한다
30+
// 시간복잡도: O(N), 공간복잡도: O(N)
31+
public List<String> decode(String str) {
32+
// write your code here
33+
List<String> answer = new ArrayList<>();
34+
var charArray = str.toCharArray();
35+
for (int i=0; i<charArray.length; i++) {
36+
if (charArray[i] == SEPERATOR) {
37+
var size = (int) charArray[i-1];
38+
char[] word = new char[size];
39+
System.arraycopy(charArray, i + 1, word, 0, size);
40+
41+
i+=size;
42+
answer.add(String.valueOf(word));
43+
}
44+
}
45+
46+
return answer;
47+
}
48+
}

0 commit comments

Comments
 (0)