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 之类的方法。本题的宗旨是需要您自己实现 “编码” 和 “解码” 算法。
解题
encode 的目的是把字符串数组全部按照某种形式连接起来变成一个字符串。decode 的目的就是把一个长的字符串切割出一个字符串数组,还原成 encode 之前的状态。encode 时,对每一个字符串,先统计它的长度,长度为 int 类型,在 Java 中是占了 4 个字节,我们把这 4 个字节用一个长度为 4 的字符串记录下来,具体操作如下: 用 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;
}
}