开始我想差了,以为encode一定要减少size。。其实未必如此,我们可以把我们想保存的信息通通存在encoded string里面
可以以这种格式:
string_size|string
每次只需要知道开始的位置,|的位置,就能得到size,进而得到结束的位置,进而得到下一个循环开始的位置,就成了一个完美的循环
代码如下:
public class Codec {
// Encodes a list of strings to a single string.
public String encode(List<String> strs) {
// append size + '|'
StringBuilder sb = new StringBuilder();
for (String s : strs) {
sb.append(s.length()).append("|").append(s);
}
return sb.toString();
}
// Decodes a single string to a list of strings.
public List<String> decode(String s) {
List<String> result = new ArrayList<>();
int idx = 0;
while (idx < s.length()) {
int pipe = s.indexOf("|", idx);
int sz = Integer.valueOf(s.substring(idx, pipe));
idx = pipe + sz + 1;
result.add(s.substring(pipe + 1, idx));
}
return result;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(strs));