LeetCode 271. Encode and Decode Strings

原题链接在这里:https://leetcode.com/problems/encode-and-decode-strings/

题目:

Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.

Machine 1 (sender) has the function:

string encode(vector<string> strs) {
  // ... your code
  return encoded_string;
}

Machine 2 (receiver) has the function:

vector<string> decode(string s) {
  //... your code
  return strs;
} 

So Machine 1 does:

string encoded_string = encode(strs);

and Machine 2 does:

vector<string> strs2 = decode(encoded_string);

strs2 in Machine 2 should be the same as strs in Machine 1.

Implement the encode and decode methods.

题解:

encode 时维护一个stringbuilder, 对于每一个string, sb append 该string长度 + "/" + string内容.

decode 时开始index = 0, while index < s.length(), 利用indexOf("/", fromIndex)找index 后面第一个 "/"的index, index 与 "/"index 之间是长度,解析后面该长度的string, 更新index到"/"index + 1 + len.

Time Complexity: encode, O(n). decode, O(n). n是strs list的所有string包含所有char的个数.

Space: O(n). StringBuilder sb 大小.

AC Java:

 1 public class Codec {
 2 
 3     // Encodes a list of strings to a single string.
 4     public String encode(List<String> strs) {
 5         if(strs == null || strs.size() == 0){
 6             return "";
 7         }
 8         StringBuilder sb = new StringBuilder();
 9         for(String s : strs){
10             int len = s.length();
11             sb.append(len).append("/");
12             sb.append(s);
13         }
14         return sb.toString();
15     }
16 
17     // Decodes a single string to a list of strings.
18     public List<String> decode(String s) {
19         List<String> res = new ArrayList<String>();
20         if(s == null || s.length() == 0){
21             return res;
22         }
23         int index = 0;
24         while(index < s.length()){
25             int forwardInd = s.indexOf("/", index);
26             int len = Integer.valueOf(s.substring(index, forwardInd));
27             res.add(s.substring(forwardInd+1,forwardInd+1+len));
28             index = forwardInd + 1 + len;
29         }
30         return res;
31     }
32 }
33 
34 // Your Codec object will be instantiated and called as such:
35 // Codec codec = new Codec();
36 // codec.decode(codec.encode(strs));

类似Serialize and Deserialize Binary TreeSerialize and Deserialize N-ary Tree.

posted @ 2016-03-04 09:37  Dylan_Java_NYC  阅读(453)  评论(0编辑  收藏  举报