[Leetcode] Encode and Decode Strings

Source: Internet
Author: User

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);

strs2In 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.