Skip to content

Commit 03adfe9

Browse files
committed
encode and decode strings solved
1 parent e21bc90 commit 03adfe9

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
4+
public class Codec {
5+
String SPLIT = ":";
6+
7+
// Encodes a list of strings to a single string.
8+
public String encode(List<String> strs) {
9+
StringBuilder encoded = new StringBuilder();
10+
11+
for(String str : strs) {
12+
encoded.append(str.length()).append(SPLIT).append(str);
13+
}
14+
15+
return encoded.toString();
16+
}
17+
18+
// Decodes a single string to a list of strings.
19+
public List<String> decode(String s) {
20+
List<String> decoded = new ArrayList<>();
21+
22+
int pointer = 0;
23+
while(pointer < s.length()) {
24+
int index = s.indexOf(SPLIT, pointer);
25+
int length = Integer.parseInt(s.substring(pointer, index));
26+
27+
String str = s.substring(index + 1, index + 1 + length);
28+
decoded.add(str);
29+
30+
pointer = index + 1 + length;
31+
}
32+
33+
return decoded;
34+
}
35+
}
36+
37+
// Your Codec object will be instantiated and called as such:
38+
// Codec codec = new Codec();
39+
// codec.decode(codec.encode(strs));

0 commit comments

Comments
 (0)