271. Encode and Decode Strings

8 阅读1分钟

image.png

Solution

Tricky part is to figure out how to encode the string.

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();
    }

    // "hello", "//", "world", "" "1"
    // hello////world//1/ -> append '/', wont work
    // 5hello/2///5world0/11/ -> len + append /, wont work (cant decode len)
    // 5/hello2///5/world0/1/1

    // Decodes a single string to a list of strings.
    public List<String> decode(String s) {
        List<String> res = new ArrayList<>();
        for (int i = 0; i < s.length(); i++) {
            int idx = s.indexOf('/', i);// first index of '/'' after ith char in string
            int len = Integer.parseInt(s.substring(i, idx)); 
            String str = s.substring(idx + 1, idx + 1 + len);
            res.add(str);
            i = idx + len; // since for loop makes i + 1 later
        }
        return res;
    }
}