[LeetCode 271] Encode and Decode

2019-06-25  本文已影响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:

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));
上一篇 下一篇

猜你喜欢

热点阅读