Encode and Decode Strings


这题是trick是先存一个str的length,然后存一个分隔符,然后存str。在decode方法里,调用indexOf(分隔符,fromIndex)这个方法,来获取word的位置。

public class Codec {

    // Encodes a list of strings to a single string.
    public String encode(List<String> strs) {
        StringBuffer sb = new StringBuffer();
        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) {
        List<String> result = new ArrayList<String>();

        int i = 0;
        while (i < s.length()) {
            int index = s.indexOf('#', i);
            int wordLength = Integer.parseInt(s.substring(i, index));
            String word = s.substring(index + 1, index + wordLength + 1);
            result.add(word);
            i = index + wordLength + 1;
        }
        return result;
    }
}

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

results matching ""

    No results matching ""