271. Encode and Decode Strings

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.

Solution:...+ s.length() + '/' + s + ...;

思路:将strs放在一个string里要能够提取出来,主要是要知道各个str的长度。那么就可以将str的长度len放在str前面,但是有可能str的开头就是数字,所以加一个separator '/' 这样一来,收到一串string,找到第一个'/',前面是len,在第一个'/'后提取len个字符,循环下去。
(Note: 所以这里的上separator只要不是char(数字)别的都可以)

Time Complexity: O(N) Space Complexity: O(1)

Solution Code:

class Codec {
    
    // Encodes a list of strings to a single string.
    public String encode(List<String> strs) {
        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> ret = new ArrayList<String>();
        int i = 0;
        while(i < s.length()) {
            int slash = s.indexOf('*', i);
            int size = Integer.valueOf(s.substring(i, slash));
            ret.add(s.substring(slash + 1, slash + size + 1));
            i = slash + size + 1;
        }
        return ret;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容