forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncodeAndDecodeStrings.java
More file actions
31 lines (28 loc) · 910 Bytes
/
EncodeAndDecodeStrings.java
File metadata and controls
31 lines (28 loc) · 910 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
31
import java.util.LinkedList;
import java.util.List;
public class EncodeAndDecodeStrings {
/**
* 非常巧妙,字符串长度 + '/' + 字符串
* @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> list = new LinkedList<String>();
for (int i = 0; i < s.length(); ) {
int index = s.indexOf("/", i);
int size = Integer.parseInt(s.substring(i, index));
i = index + 1 + size;
list.add(s.substring(index + 1, i));
}
return list;
}
}