Encode and decode Strings - Teeeeeebag/LeetCode GitHub Wiki

  1. mistake made: I thought length is a single digit again which is stupid. We have to use "/" after length to tell us how many digits the length is.
public class Codec {

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

    // Decodes a single string to a list of strings.
    public List<String> decode(String s) {
        ArrayList<String> res = new ArrayList<>();
        if(s.length() == 0){
            return res;
        }
        int p = 0;
        while (p < s.length()){
            int end = s.indexOf('/', p);
            int len = Integer.parseInt(s.substring(p, end));
            p = end + 1;
            res.add(s.substring(p, p+len));
            p = p+len;
        }
        return res;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(strs));
⚠️ **GitHub.com Fallback** ⚠️