Friday, November 27, 2015

[leetcode] Encode and Decode String

收录一个更加简单的方法(同样思想)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Codec {

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

    // Decodes a single string to a list of strings.
    public List<String> decode(String s) {
        List<String> ret = new ArrayList<String>();
        int i = 0;
        while(i < s.length()) {
            int slash = s.indexOf('/', i);
            int size = Integer.valueOf(s.substring(i, slash));
            ret.add(s.substring(slash + 1, slash + size + 1));
            i = slash + size + 1;
        }
        return ret;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class Codec {

    // Encodes a list of strings to a single string.
    public String encode(List<String> strs) {
        if (strs == null || strs.size() == 0) return "#-1#";
        String header = "#";
        for (int i = 0; i < strs.size(); i++){
            header = header+strs.get(i).length()+",";
        }

        header = header.substring(0, header.length()-1)+"#";
        String body = "";
        for (int i = 0; i < strs.size(); i++){
            body += strs.get(i);
        }
        return header+body;
    }

    // Decodes a single string to a list of strings.
    public List<String> decode(String s) {
        int[]lengths = readHeader(s);
        List<String> result = new ArrayList<String>();
        if (lengths[0] == -1) return result;
        int starting = lengths[lengths.length-1];
        for (int i = 0; i < lengths.length-1; i++){
            if (lengths[i] == 0){
                result.add("");
            }else{
                result.add(s.substring(starting, starting+lengths[i]));
            }
            starting += lengths[i];
        }
        return result;
    }
    
    int[] readHeader(String s){
        int i = 2;
        for (; i < s.length() && s.charAt(i) != '#'; i++);
        String header = s.substring(1, i);
        String[]temp = header.split(",");
        int[]result = new int[temp.length+1];
        for (int j = 0; j < temp.length; j++){
            result[j] = (new Integer(temp[j])).intValue();
        }
        result[result.length-1] = i+1;//starting index
        return result;
    }
}

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

No comments:

Post a Comment