Skip to content

Commit 6ce47d8

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

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed
Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,15 @@
11
public 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
}

0 commit comments

Comments
 (0)