Skip to content

Commit d74ceb7

Browse files
donghyeon95donghyeon95
authored andcommitted
feat: Encode and Decode Strings #238
1 parent 66fab2a commit d74ceb7

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import java.util.ArrayList;
2+
import java.util.Arrays;
3+
import java.util.List;
4+
import java.util.stream.Collectors;
5+
6+
public class Solution {
7+
/*
8+
* @param strs: a list of strings
9+
* @return: encodes a list of strings to a single string.
10+
*/
11+
String cDel = "&";
12+
String sDel = ";";
13+
14+
// Encodes a list of strings to a single string
15+
public String encode(List<String> strs) {
16+
if (strs.isEmpty()) return null;
17+
18+
StringBuilder result = new StringBuilder();
19+
for (int i =0; i<strs.size(); i++) {
20+
String str = strs.get(i);
21+
StringBuilder temp = new StringBuilder();
22+
for (char c : str.toCharArray()) {
23+
temp.append((int) c).append(cDel);
24+
}
25+
26+
result.append(temp);
27+
if (i != strs.size()-1) result.append(sDel);
28+
}
29+
return result.toString();
30+
}
31+
32+
// Decodes a single string to a list of strings
33+
public List<String> decode(String str) {
34+
if (str==null)
35+
return new ArrayList<>();
36+
37+
List<String> result = new ArrayList<>();
38+
String[] strs = str.split(sDel, -1);
39+
for (String s : strs) {
40+
if (s.isEmpty()) {
41+
result.add("");
42+
continue;
43+
}
44+
String[] chars = s.split(cDel);
45+
String decoded = Arrays.stream(chars)
46+
.filter(sr -> !sr.isEmpty())
47+
.mapToInt(Integer::parseInt)
48+
.mapToObj(ascii -> (char) ascii)
49+
.map(String::valueOf)
50+
.collect(Collectors.joining());
51+
result.add(decoded);
52+
}
53+
return result;
54+
}
55+
}
56+
57+

0 commit comments

Comments
 (0)