Star

Leetcode 271. Encode and Decode Strings

Question:

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.

Machine 1 (sender) has the function:

encode(vector strs) {
1
2
3
// ... your code
return encoded_string;
}

Machine 2 (receiver) has the function:

decode(string s) {
1
2
3
//... your code
return strs;
}

So Machine 1 does:

1
string encoded_string = encode(strs);

and Machine 2 does:

1
vector<string> strs2 = decode(encoded_string);

strs2 in Machine 2 should be the same as strs in Machine 1.

Implement the encode and decode methods.

Note:

  • The string may contain any possible characters out of 256 valid ascii characters. Your algorithm should be generalized enough to work on any possible characters.
  • Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.
  • Do not rely on any library method such as eval or serialize methods. You should implement your own encode/decode algorithm.

Explanation:

乍一看,也不知道说的是什么。其实题意是给一个list的字符串,先要拼成一整个字符串,是encode。然后把这整个字符拆回一个list的字符。 所以考点是如何合理地分隔,然后还能识别出来。 这哪儿是算法,其实考的是Serilization这个计算机系统中的基本概念。

1
串行化(Serialization)是计算机科学中的一个概念,它是指将对象存储到介质(如文件、内存缓冲区等)中或是以二进制方式通过网络传输。之后可以通过反串行化从这些连续的字节(byte)数据重新构建一个与原始对象状态相同的对象,因此在特定情况下也可以说是得到一个副本,但并不是所有情况都这样。

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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(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;
}
}