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.
The difficulty is not in the character encryption, but in how to separate the various strings. The original character already occupies any available 256, so you can't simply select a delimiter and use split.
The last method is to encrypt with the length + ' # ' + the form of real strings to add (practice really feasible, even if the actual delimiter character, because you explain the length of the time you take it out after the next use indexof will not affect. And the first delimiter must come from a real delimiter, so there's no problem with recursion.
Decrypt every 1.indexOf (' # ', idx), starting at the point where the pointer is pointing to find the first delimiter. 2. The last pointer to the current segmentation point after the semantic understanding is the string length. 3. Remove the string later.
Realize:
Public classCodec {//encodes a list of strings to a single string. PublicString Encode (list<string>STRs) {StringBuilder SB=NewStringBuilder (); for(inti = 0; I < strs.size (); i++) {sb.append (Strs.get (i). Length ()); Sb.append (‘#‘); Sb.append (Strs.get (i)); } returnsb.tostring (); } //decodes a single string to a list of strings. PublicList<string>Decode (String s) {List<String> result =NewArraylist<>(); intIDX = 0; while(IDX <s.length ()) { intCut = S.indexof (' # ', IDX); intLength =Integer.parseint (s.substring (idx, cut)); Result.add (s.substring (Cut+ 1, cut + 1 +length)); IDX= cut + length + 1; } returnresult; }}//Your Codec object would be instantiated and called as such://Codec Codec = new Codec ();//Codec.decode (Codec.encode (STRs));
Leetcode271-encode and Decode Strings-medium