Design an algorithm to encodea list of stringstoa string. The encoded string is then sent over the network and is decoded back to the original list of strings.
vector<string> decode(string s) {
//... your code
return strs;
}
So Machine 1 does:
string encoded_string = encode(strs);
and Machine 2 does:
vector<string> strs2 = decode(encoded_string);
strs2in Machine 2 should be the same asstrsin Machine 1.
Implement theencodeanddecodemethods.
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 asevalor serialize methods. You should implement your own encode/decode algorithm.
/* * @param strs: a list of strings * @return: encodes a list of strings to a single string. */publicStringencode(List<String> strs) {// write your code hereif (strs ==null||strs.size() ==0) {return""; }StringBuilder sb =newStringBuilder();for (String s : strs) {char[] sc =s.toCharArray();for (char c : sc) {if (c ==':') {sb.append(':'); } sb.append(c); }sb.append(":;"); }returnsb.toString();}/* * @param str: A string * @return: dcodes a single string to a list of strings */publicList<String>decode(String s) {List<String> res =newArrayList<>();if (s ==null||s.length() ==0) {return res; }// 这里用split来分开":;"是不行的,有些[""]的test case不过int i =0;StringBuilder sb =newStringBuilder();char[] sc =s.toCharArray();while (i <sc.length) {if (sc[i] ==':') {if (sc[i +1] ==';') {res.add(sb.toString()); sb =newStringBuilder(); i +=2; } else {sb.append(':'); i +=2; } } else {sb.append(sc[i]); i++; } }return res;}// 下面的做法不行:publicList<String>decode(String str) {// write your code hereList<String> res =newArrayList<>();if (str ==null||str.length() ==0) {return res; }String[] parts =str.split(":;");for (String part : parts) {StringBuilder sb =newStringBuilder();char[] pc =part.toCharArray();for (int i =0; i <pc.length; i++) {if (pc[i] !=':') {sb.append(pc[i]); } else {// ::=》 :,所以跳过一个 i++; } }res.add(sb.toString()); }return res;}