开始我想差了,以为encode一定要减少size。。其实未必如此,我们可以把我们想保存的信息通通存在encoded string里面

    可以以这种格式:

    • string_size|string

    每次只需要知道开始的位置,|的位置,就能得到size,进而得到结束的位置,进而得到下一个循环开始的位置,就成了一个完美的循环

    代码如下:

    1. public class Codec {
    2. // Encodes a list of strings to a single string.
    3. public String encode(List<String> strs) {
    4. // append size + '|'
    5. StringBuilder sb = new StringBuilder();
    6. for (String s : strs) {
    7. sb.append(s.length()).append("|").append(s);
    8. }
    9. return sb.toString();
    10. }
    11. // Decodes a single string to a list of strings.
    12. public List<String> decode(String s) {
    13. List<String> result = new ArrayList<>();
    14. int idx = 0;
    15. while (idx < s.length()) {
    16. int pipe = s.indexOf("|", idx);
    17. int sz = Integer.valueOf(s.substring(idx, pipe));
    18. idx = pipe + sz + 1;
    19. result.add(s.substring(pipe + 1, idx));
    20. }
    21. return result;
    22. }
    23. }
    24. // Your Codec object will be instantiated and called as such:
    25. // Codec codec = new Codec();
    26. // codec.decode(codec.encode(strs));