Java solution inspired by http protocol.


  • 1
    E

    public class Codec {

    // Encodes a list of strings to a single string.
    public String encode(List<String> strs) {
        StringBuilder msg = new StringBuilder();
        int n = strs.size();
        String total_n = String.format("%4d", n);
        msg.append(total_n);
        for (String str : strs) {
            int str_n = str.length();
            
            String str_L = String.format("%4d", str_n);
            msg.append(str_L);
            msg.append(str);
        }
        System.out.println(msg.toString());
        return msg.toString();
    }
    
    // Decodes a single string to a list of strings.
    public List<String> decode(String s) {
        System.out.println(s.length());
        List<String> result = new ArrayList<>();
        String total_n = s.substring(0, 4);
        int n = Integer.parseInt(total_n.trim());
        int offset = 0 + 4;
        for (int i = 0; i < n; i++) {
            String str_L = s.substring(offset, offset + 4);
            
            int str_n = 0;
            if (!str_L.trim().equals("")) {
                str_n = Integer.parseInt(str_L.trim());
            }
            offset = offset + 4;
            if (str_n == 0) {
                result.add("");
            } else {
                String nStr = s.substring(offset, offset + str_n);
                result.add(nStr);
            }
            offset = offset + str_n;
        }
        
        return result;
    }
    

    }

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


  • 0
    Y

    What about the case: when there is a string in the list whose length is more than 4?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.