Encode and Decode Strings Solutions

Source: Internet
Author: User

Question

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.
Solution 1--JSON format

The first method is to refer to the JSON rules.

Encode: We encapsulate the input string array as an array in JSON. [(left bracket) and] (right bracket) indicates the end of the beginning. The middle of the separation, (comma). Then for each string, is wrapped in double quotes.

Since there may be double quotes or back slash (\) in the string, we need to escape the two symbols. method is to add a back slash

such as the original string \ "AAFG", \\\ "aafg\"

There are more complex string handling methods in JSON. But our goal here is to make encode, and then decode the same string, so it doesn't have to be that complicated.

Decode treatment principles are as follows

1. A Boolean variable record should currently be the beginning of the next string or the end of the current string

2. Encounter bracket, based on start/end, create a new empty string/Save the current string in the result

3. Touch back slash to see if the next element is back slash/bracket, and if so, add the next element to the string, and add one to the count.

1  Public classCodec {2     Private Final Charstart = ' [';3     Private Final Charend = '] ';4     Private Final CharInclude = ' "';5     Private Final CharStrsplit = ', ';6 7     //encodes a list of strings to a single string.8      PublicString Encode (list<string>STRs) {9StringBuilder SB =NewStringBuilder ();Ten sb.append (start); One          for(String str:strs) { A sb.append (include); -             intLen =str.length (); -              for(inti = 0; i < Len; i++) { the                 CharCurrent =Str.charat (i); -                 if(Current = = ' "' | | current = = ' \ \ ') { -Sb.append (' \ \ '); -                 } + Sb.append (current); -             } + sb.append (include); A sb.append (strsplit); at         } - sb.append (end); -         returnsb.tostring (); -     } -  -     //decodes a single string to a list of strings. in      PublicList<string>Decode (String s) { -list<string> result =NewArraylist<string>(); to         if(s = =NULL|| S.length () < 1) { +             returnresult; -         } the         intLen =s.length (); *         if(S.charat (0)! = Start | | S.charat (len-1)! =end) { $             returnresult;Panax Notoginseng         } -         BooleanStartsymbol =true; theStringBuilder SB =NewStringBuilder (); +          for(inti = 1; i < len-1; i++) { A             CharCurrent =S.charat (i); the             if(Current = =include) { +                 if(startsymbol) { -SB =NewStringBuilder (); $}Else { $ Result.add (sb.tostring ()); -                 } -Startsymbol =!Startsymbol; the                 Continue; -             }Wuyi             if(current = = Strsplit &&Startsymbol) { the                 Continue; -             } Wu             if(current = = ' \ \ ') { -                 CharNext = S.charat (i + 1)); About                 if(next = ' \ \ ' | | next = ' "')) { $ Sb.append (next); -i++; -                     Continue; -                 } A             } + Sb.append (current); the         } -         returnresult; $     } the } the  the //Your Codec object would be instantiated and called as such: the //Codec Codec = new Codec (); - //Codec.decode (Codec.encode (STRs));

Solution 2

Takes advantage of the string int indexOf (int ch, int fromIndex) function in Java.

The length of the string and the string are also stored.

1  Public classCodec {2 3     //encodes a list of strings to a single string.4      PublicString Encode (list<string>STRs) {5StringBuilder SB =NewStringBuilder ();6          for(String str:strs) {7Sb.append (Str.length ()). Append ('/'). append (str);8         }9         returnsb.tostring ();Ten     } One  A     //decodes a single string to a list of strings. -      PublicList<string>Decode (String s) { -list<string> result =NewArraylist<string>(); the         intLength =s.length (); -         inti = 0; -          while(I <length) { -             intSlash = S.indexof ('/'), i); +             intSize =integer.valueof (s.substring (i, Slash)); -Result.add (s.substring (slash + 1, slash + size + 1)); +i = slash + size + 1; A         } at         returnresult; -     } -}

Encode and Decode Strings answers

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.