Encode and Decode Strings
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.
{"abc", "123", "D"}, 3#abc3#1231#d:res + = to_string (Str.length ()) + "#" + str;
1 classCodec {2 Public:3 4 //encodes a list of strings to a single string.5 stringEncode (vector<string>&STRs) {6 stringRes;7 for(Auto str:strs) {8Res + = to_string (Str.length ()) +"#"+str;9 }Ten returnRes; One } A - //decodes a single string to a list of strings. -vector<string> Decode (strings) { thevector<string>Res; - intIDX =0, POS, size; - while(IDX <s.length ()) { -pos = S.find ('#', idx); + if(pos = =string:: NPOs) Break; -Size = Stoi (s.substr (IDX, pos-idx)); +Res.push_back (S.substr (pos+1, size)); AIDX = pos +1+size; at } - returnRes; - } - }; - - //Your Codec object would be instantiated and called as such: in //Codec Codec; - //Codec.decode (Codec.encode (STRs));
[Leetcode] Encode and Decode Strings