Simple java solution with comments


  • 0
    A
    public class Codec {
    
    // Encodes a list of strings to a single string.
    public static String encode(List<String> strs) {
        if (strs.size() == 0) return null;
        StringBuilder builder = new StringBuilder();
        for(String s : strs) {
            // encode with "LENGTH:STRING"
            builder.append(s.length()).append(":").append(s);
        }
        return builder.toString();
    }
    
    // Decodes a single string to a list of strings.
    public static List<String> decode(String encoded) {
        LinkedList<String> strings = new LinkedList<>();
        if (encoded == null) return strings;
        int p=0,i=0;
        while(i<encoded.length()) {
            if (encoded.charAt(i) == ':') {
                // get the length
                int length = Integer.parseInt(encoded.substring(p, i));
                // extract the string
                strings.add(encoded.substring(++i, i=i+length));
                // look for next
                p = i++;
            } else {
                i++;
            }
        }
        return strings;
    }
    

    }


Log in to reply
 

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