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.
请你设计一个算法,可以将一个 字符串列表 编码成为一个 字符串。这个编码后的字符串是可以通过网络进行高效传送的,并且可以在接收端被解码回原来的字符串列表。
string encode(vector<string> strs) {
// ... your code
return encoded_string;
}
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 方法。
解题
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;
}
}
原创文章,作者:栈长,如若转载,请注明出处:https://www.cxyquan.com/11907.html