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:
string encode(vector<string> strs) { // ... your code return encoded_string; }
public class Codec { // Encodes a list of strings to a single string. public String encode(List<String> strs) { StringBuilder sb = new StringBuilder(); for (String str: strs) { int len = str.length(); sb.append(len).append("/").append(str); } return sb.toString(); } // Decodes a single string to a list of strings. public List<String> decode(String s) { List<String> res = new ArrayList<>(); int i = 0; while (i < s.length()) { int slash = s.indexOf("/", i); int len = Integer.valueOf(s.substring(i, slash)); res.add(s.substring(slash + 1, slash + 1 + len)); i = slash + 1 + len; } return res; } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.decode(codec.encode(strs));