天天看点

​LeetCode刷题实战271:字符串的编码与解码

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 字符串的编码与解码,我们先来看题面:

https://leetcode-cn.com/problems/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.

请你设计一个算法,可以将一个 字符串列表 编码成为一个 字符串。这个编码后的字符串是可以通过网络进行高效传送的,并且可以在接收端被解码回原来的字符串列表。

1 号机(发送方)有如下函数:

string encode(vector<string> strs) {
  // ... your code
  return encoded_string;
}
           

2 号机(接收方)有如下函数:

vector<string> decode(string s) {
  //... your code
  return strs;
}
           
1 号机(发送方)执行:

string encoded_string = encode(strs);
2 号机(接收方)执行:

vector<string> strs2 = decode(encoded_string);
此时,2 号机(接收方)的 strs2 需要和 1 号机(发送方)的 strs 相同。

请你来实现这个 encode 和 decode 方法。
           

注意:因为字符串可能会包含 256 个合法 ascii 字符中的任何字符,所以您的算法必须要能够处理任何可能会出现的字符。请勿使用 “类成员”、“全局变量” 或 “静态变量” 来存储这些状态,您的编码和解码算法应该是非状态依赖的。请不要依赖任何方法库,例如 eval 又或者是 serialize 之类的方法。本题的宗旨是需要您自己实现 “编码” 和 “解码” 算法。

解题

https://blog.csdn.net/qq_29051413/article/details/108531033

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

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

encode 时,对每一个字符串,先统计它的长度,长度为 int 类型,在 Java 中是占了 4 个字节,我们把这 4 个字节用一个长度为 4 的字符串记录下来,具体操作如下:

​LeetCode刷题实战271:字符串的编码与解码

用 4 个字符长度的字符串来表示后面接着的字符串长度。

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

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;
    }
}
           

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-260题汇总,希望对你有点帮助!

LeetCode刷题实战261:以图判树

LeetCode刷题实战262:行程和用户

LeetCode刷题实战263:丑数

LeetCode刷题实战264:丑数 II

LeetCode刷题实战265:粉刷房子II

LeetCode刷题实战266:回文排列

LeetCode刷题实战267:回文排列II

LeetCode刷题实战268:丢失的数字

LeetCode刷题实战269:火星词典

​LeetCode刷题实战271:字符串的编码与解码