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