1 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. 2 3 Machine 1 (sender) has the function: 4 5 string encode(vectorstrs) { 6 // ... your code 7 return encoded_string; 8 } 9 Machine 2 (receiver) has the function:10 vector decode(string s) {11 //... your code12 return strs;13 }14 So Machine 1 does:15 16 string encoded_string = encode(strs);17 and Machine 2 does:18 19 vector strs2 = decode(encoded_string);20 strs2 in Machine 2 should be the same as strs in Machine 1.21 22 Implement the encode and decode methods.23 24 Note:25 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.26 Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.27 Do not rely on any library method such as eval or serialize methods. You should implement your own encode/decode algorithm.
本题难点在于如何在合并后的字符串中,区分出原来的每一个子串。这里我采取的编码方式,是将每个子串的长度先赋在前面,然后用一个#
隔开长度和子串本身。这样我们先读出长度,就知道该读取多少个字符作为子串了。
注意
为了简化代码,这里使用了indexOf
和substring
这两个属于String的API,实际上复杂度和遍历是一样的。
1 public class Codec { 2 3 // Encodes a list of strings to a single string. 4 public String encode(Liststrs) { 5 StringBuffer res = new StringBuffer(); 6 for (int i=0; i decode(String s) {16 List result = new ArrayList ();17 while (s.length() > 0) {18 int i = s.indexOf("#");19 int count = Integer.parseInt(s.substring(0, i));20 result.add(s.substring(i+1, i+1+count));21 s = s.substring(i+1+count);22 }23 return result;24 }25 }26 27 // Your Codec object will be instantiated and called as such:28 // Codec codec = new Codec();29 // codec.decode(codec.encode(strs));