A straightforward java solution


  • 0
    Z

    public class Codec {

    // Encodes a list of strings to a single string.
    public String encode(List<String> strs) {
        
        StringBuilder builder = new StringBuilder();
        
        for(String str : strs) {
            builder.append(str.length() + "#" + str);
        }
        
        return builder.toString();
    }
    
    // Decodes a single string to a list of strings.
    public List<String> decode(String s) {
        int start = 0, split = 0, len;
        List<String> ans = new ArrayList<>();
        
        if(s.length() == 0)
            return ans;
        
        while(start < s.length() && (split = s.indexOf('#' , start)) != -1) {
            len = Integer.parseInt(s.substring(start , split));
            
            ans.add(s.substring(split + 1, split + len + 1));
            start = split + len + 1;
        }
        
        return ans;
    }
    

    }

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


Log in to reply
 

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