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.
Idea: Add the length of each string before it and a% character.
1 classCodec {2 Public:3 4 //encodes a list of strings to a single string.5 stringEncode (vector<string>&STRs) {6 stringRes;7 for(inti =0; I < strs.size (); i++)8Res + = std::to_string (Strs[i].size ()) +"%"+Strs[i];9 returnRes;Ten } One A //decodes a single string to a list of strings. -vector<string> Decode (strings) { -vector<string>Res; the intCurind =0; - intMark = S.find ("%"); - while(Mark! = std::string:: NPOs) { - intLen = Std::stoi (S.substr (Curind, Mark-curind)); + if(len) Res.push_back (S.substr (Mark +1, Len)); - //In case it's an empty string + ElseRes.push_back (""); ACurind = Mark + len +1; atMark = S.find ("%", curind); - } - returnRes; - } - }; - in //Your Codec object would be instantiated and called as such: - //Codec Codec; to //Codec.decode (Codec.encode (STRs));
Encode and Decode Strings--Leetcode