https://leetcode.com/problems/encode-and-decode-strings/description/
这道题是序列化反序列化LIST<STRING> 因为STRING可能可以包含任何字符。所以我采用的是JDK的做法。先存STRING的长度,然后打一个空格,随后存STRING。
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(str);
}
return sb.toString();
}
// Decodes a single string to a list of strings.
public List<String> decode(String s) {
List<String> res = new ArrayList<>();
char[] cs = s.toCharArray();
for(int i = 0; i < cs.length;){
StringBuilder len = new StringBuilder();
StringBuilder content = new StringBuilder();
while(cs[i]!=' '){
len.append(cs[i]);
i++;
}
i++;
int l = Integer.parseInt(len.toString());
for(int j=0;j<l;j++)
content.append(cs[i++]);
res.add(content.toString());
}
return res;
}
}