美文网首页
[LeetCode 271] Encode and Decode

[LeetCode 271] Encode and Decode

作者: 灰睛眼蓝 | 来源:发表于2019-06-25 16:07 被阅读0次

Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is 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 be the same as strs in Machine 1.

Implement the encode and decode methods.

Note:

  • The string may contain any possible characters out of 256 valid ascii characters. Your algorithm should be generalized enough to work on any possible characters.
  • Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.
  • Do not rely on any library method such as eval or serialize methods. You should implement your own encode/decode algorithm.

Solution

  1. encode的时候每次记录下每个String的长度,并记录入encode的结果中
  2. decode的时候,根据每个String的长度来decode
public class Codec {

    // Encodes a list of strings to a single string.
    public String encode(List<String> strs) {
        StringBuffer out = new StringBuffer();
        for (String s : strs) {
            out.append (s.length ()).append ("/").append (s);
        }
        return out.toString();
    }

    // Decodes a single string to a list of strings.
    public List<String> decode(String s) {
        System.out.println (s);
        List<String> res = new ArrayList<>();
        // String[] array = s.split(" # ", -1);
    
        int index = 0;
        while (index < s.length ()) {
            int number = 0;
            if (Character.isDigit (s.charAt (index))) {
                while (index < s.length () && Character.isDigit (s.charAt (index))) {
                    number = number * 10 + s.charAt (index) - '0';
                    index++;
                }
                
                System.out.println ("start: " + (index + 1) + " end: " + (index + 1 + number));
                String temp = s.substring (index + 1, index + 1 + number);
                res.add (temp);
                index = index + number + 1;
            }
        }
        return res;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(strs));

相关文章

网友评论

      本文标题:[LeetCode 271] Encode and Decode

      本文链接:https://www.haomeiwen.com/subject/bfcxcctx.html