Design a algorithm to encode a list of strings to a string. The encoded string is then sent over the network and are decoded back to the original list of strings.
Machine 1 (sender) has the function:
String encode (vector<string> STRs) { //... your code return encoded_string;}
Machine 2 (receiver) has the function:
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);
strs2
In Machine 2 should is the same as in Machine strs
1.
Implement the encode
and decode
methods.
Note:
- The string may contain any possible characters out of the valid ASCII characters. Your algorithm should is generalized enough to work on any possible characters.
- Don't use the class member/global/static variables to store states. Your encode and decode algorithms should be stateless.
- Rely on any library method such as
eval
or Serialize methods. You should implement your own Encode/decode algorithm.
classCodec { Public: //encodes a list of strings to a single string. stringEncode (vector<string>&STRs) { stringRes; for(Auto Str:strs) res+=to_string (Str.size ()) +"@"+str; returnRes; } //decodes a single string to a list of strings.vector<string> Decode (strings) {vector<string>Res; intHead =0; while(head<s.size ()) { intpos = S.find ("@", head); intLen = Stoll (S.substr (head,pos-head)); stringstr = S.SUBSTR (pos+1, Len); Res.push_back (str); Head= pos+1+Len; } returnRes; }};//Your Codec object would be instantiated and called as such://Codec Codec;//Codec.decode (Codec.encode (STRs));
271. Encode and Decode Strings