【LeetCode(Java) - 271】字符串的编码与解码

1、题目描述

在这里插入图片描述

2、解题思路

  encode 的目的是把字符串数组全部按照某种形式连接起来变成一个字符串。

  decode 的目的就是把一个长的字符串切割出一个字符串数组,还原成 encode 之前的状态。

  encode 时,对每一个字符串,先统计它的长度,长度为 int 类型,在 Java 中是占了 4 个字节,我们把这 4 个字节用一个长度为 4 的字符串记录下来,具体操作如下:
在这里插入图片描述
  用 4 个字符长度的字符串来表示后面接着的字符串长度。

decode 的时候,一开始先把前 4 个字符组成的字符串转为 int 类型数字,就可以或者从索引 5 开始的有效字符串长度。

3、解题代码

public 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(intToString(s));
            sb.append(s);
        }
        return sb.toString();
    }

    // Decodes a single string to a list of strings.
    public List<String> decode(String s) {
    
    
        int i = 0, n = s.length();
        List<String> output = new ArrayList();
        while (i < n) {
    
    
            int length = stringToInt(s.substring(i, i + 4));
            i += 4;
            output.add(s.substring(i, i + length));
            i += length;
        }
        return output;
    }

    // Encodes string length to bytes string
    public String intToString(String s) {
    
    
        int x = s.length();
        char[] bytes = new char[4];
        for (int i = 3; i >= 0; i--) {
    
    
            bytes[3 - i] = (char) (x >> (i * 8) & 0xff);
        }
        return new String(bytes);
    }

    // Decodes bytes string to integer
    public int stringToInt(String bytesStr) {
    
    
        int result = 0;
        for (char b : bytesStr.toCharArray())
            result = (result << 8) + (int) b;
        return result;
    }
}

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

猜你喜欢

转载自blog.csdn.net/qq_29051413/article/details/108531033
今日推荐