Skip to content

Commit c1f9078

Browse files
committed
659. Encode and Decode Strings modify
1 parent 33f0817 commit c1f9078

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed
Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
11
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)
54
/*
65
* @param strs: a list of strings
76
* @return: encodes a list of strings to a single string.
87
*/
98
public String encode(List<String> strs) {
109
// 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();
1415
}
1516

1617
/*
@@ -20,8 +21,14 @@ public String encode(List<String> strs) {
2021
public List<String> decode(String str) {
2122
// write your code here
2223
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+
}
2532
return output;
2633
}
2734
}

0 commit comments

Comments
 (0)