File tree 1 file changed +13
-8
lines changed
encode-and-decode-strings
1 file changed +13
-8
lines changed Original file line number Diff line number Diff line change 1
1
public class Solution {
2
- // time complexity: O(n)
3
- // space complexity: O(n)
4
- Map <Integer , String > encode = new HashMap <>();
5
2
/*
6
3
* @param strs: a list of strings
7
4
* @return: encodes a list of strings to a single string.
8
5
*/
9
6
public String encode (List <String > strs ) {
10
7
// 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 ();
14
13
}
15
14
16
15
/*
@@ -20,8 +19,14 @@ public String encode(List<String> strs) {
20
19
public List <String > decode (String str ) {
21
20
// write your code here
22
21
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
+ }
25
30
return output ;
26
31
}
27
32
}
You can’t perform that action at this time.
0 commit comments