File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
encode-and-decode-strings Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
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));
You can’t perform that action at this time.
0 commit comments