首页 > Web开发 > 详细

[LC] 271. Encode and Decode Strings

时间:2020-02-14 12:03:31      阅读:75      评论:0      收藏:0      [点我收藏+]

Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.

Machine 1 (sender) has the function:

string encode(vector<string> strs) {
  // ... your code
  return encoded_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) {
            int len = str.length();
            sb.append(len).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 len = Integer.valueOf(s.substring(i, slash));
            res.add(s.substring(slash + 1, slash + 1 + len));
            i = slash + 1 + len;
        }
        return res;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(strs));

 

[LC] 271. Encode and Decode Strings

原文:https://www.cnblogs.com/xuanlu/p/12306515.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!