File tree Expand file tree Collapse file tree 1 file changed +15
-8
lines changed
encode-and-decode-strings Expand file tree Collapse file tree 1 file changed +15
-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 <>();
2
+ // Time complexity: O(n)
3
+ // Space complexity: O(n)
5
4
/*
6
5
* @param strs: a list of strings
7
6
* @return: encodes a list of strings to a single string.
8
7
*/
9
8
public String encode (List <String > strs ) {
10
9
// write your code here
11
- int key = 0 ;
12
- for (String str : strs ) encode .put (key ++, str );
13
- return String .valueOf (key );
10
+ StringBuilder sb = new StringBuilder ();
11
+ for (String str : strs ) {
12
+ sb .append (str .length ()).append ("#" ).append (str );
13
+ }
14
+ return sb .toString ();
14
15
}
15
16
16
17
/*
@@ -20,8 +21,14 @@ public String encode(List<String> strs) {
20
21
public List <String > decode (String str ) {
21
22
// write your code here
22
23
List <String > output = new ArrayList <>();
23
- int decode = 0 ;
24
- while (decode < Integer .valueOf (str )) output .add (encode .get (decode ++));
24
+ int i = 0 ;
25
+ while (i < str .length ()) {
26
+ int idx = str .indexOf ('#' , i );
27
+ int length = Integer .parseInt (str .substring (i , idx ));
28
+ String s = str .substring (idx + 1 , idx + 1 + length );
29
+ output .add (s );
30
+ i = idx + 1 + length ;
31
+ }
25
32
return output ;
26
33
}
27
34
}
You can’t perform that action at this time.
0 commit comments