File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
encode-and-decode-strings Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 1+ public class Codec {
2+
3+ // Encodes a list of strings to a single string.
4+ public String encode (List <String > strs ) {
5+ StringBuilder sb = new StringBuilder ();
6+
7+ for (String s : strs ) {
8+ sb .append (s .length ()).append ('#' ).append (s );
9+ }
10+
11+ return sb .toString ();
12+ }
13+
14+ // Decodes a single string to a list of strings.
15+ public List <String > decode (String s ) {
16+ List <String > res = new ArrayList <>();
17+ int i = 0 ;
18+
19+ while (i < s .length ()) {
20+ int j = i ;
21+
22+ // find '#'
23+ while (s .charAt (j ) != '#' ) {
24+ j ++;
25+ }
26+
27+ int length = Integer .parseInt (s .substring (i , j ));
28+ j ++; // move past '#'
29+
30+ String word = s .substring (j , j + length );
31+ res .add (word );
32+
33+ i = j + length ; // move to next encoded segment
34+ }
35+
36+ return res ;
37+ }
38+ }
You can’t perform that action at this time.
0 commit comments