File tree Expand file tree Collapse file tree 1 file changed +13
-8
lines changed
encode-and-decode-strings Expand file tree Collapse file tree 1 file changed +13
-8
lines changed Original file line number Diff line number Diff line change 11public class Solution {
2- // time complexity: O(n)
3- // space complexity: O(n)
4- Map <Integer , String > encode = new HashMap <>();
52 /*
63 * @param strs: a list of strings
74 * @return: encodes a list of strings to a single string.
85 */
96 public String encode (List <String > strs ) {
107 // write your code here
11- int key = 0 ;
12- for (String str : strs ) encode .put (key ++, str );
13- return String .valueOf (key );
8+ StringBuilder sb = new StringBuilder ();
9+ for (String str : strs ) {
10+ sb .append (str .length ()).append ("#" ).append (str );
11+ }
12+ return sb .toString ();
1413 }
1514
1615 /*
@@ -20,8 +19,14 @@ public String encode(List<String> strs) {
2019 public List <String > decode (String str ) {
2120 // write your code here
2221 List <String > output = new ArrayList <>();
23- int decode = 0 ;
24- while (decode < Integer .valueOf (str )) output .add (encode .get (decode ++));
22+ int i = 0 ;
23+ while (i < str .length ()) {
24+ int idx = str .indexOf ('#' , i );
25+ int length = Integer .parseInt (str .substring (i , idx ));
26+ String s = str .substring (idx + 1 , idx + 1 + length );
27+ output .add (s );
28+ i = idx + 1 + length ;
29+ }
2530 return output ;
2631 }
2732}
You can’t perform that action at this time.
0 commit comments