forked from szl0072/Leetcode-Solution-Code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncodeandDecodeStrings.java
More file actions
45 lines (39 loc) · 1.09 KB
/
EncodeandDecodeStrings.java
File metadata and controls
45 lines (39 loc) · 1.09 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package leetcode;
import java.util.ArrayList;
import java.util.List;
/**
* Project Name : Leetcode
* Package Name : leetcode
* File Name : EncodeandDecodeStrings
* Creator : Edward
* Date : Oct, 2017
* Description : 271. Encode and Decode Strings
*/
public class EncodeandDecodeStrings {
/**
* time : O(n);
* space : O(n)
* @param strs
* @return
*/
// 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> res = new ArrayList<>();
int i = 0;
while (i < s.length()) {
int slash = s.indexOf('/', i);
int size = Integer.valueOf(s.substring(i, slash));
res.add(s.substring(slash + 1, slash + size + 1));
i = slash + size + 1;
}
return res;
}
}