forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbky373.java
More file actions
30 lines (28 loc) · 845 Bytes
/
bky373.java
File metadata and controls
30 lines (28 loc) · 845 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* time: O(N)
* space: O(N)
*/
public class Codec {
// Encodes a list of strings to a single string.
public String encode(List<String> strs) {
StringBuilder sb = new StringBuilder();
for (String str : strs) {
sb.append(str.length())
.append(':')
.append(str);
}
return sb.toString();
}
// Decodes a single string to a list of strings.
public List<String> decode(String s) {
List<String> decoded = new ArrayList<>();
int i = 0;
while (i < s.length()) {
int searchIndex = s.indexOf(':', i);
int chunkSize = Integer.parseInt(s.substring(i, searchIndex));
i = searchIndex + chunkSize + 1;
decoded.add(s.substring(searchIndex + 1, i));
}
return decoded;
}
}