Friday, July 15, 2016

271. Encode and Decode Strings

The idea is easy. To have a fixed length header to contain the length of the string. When decode, parse the header and get the string whose length is specified by the header.

When I revisited this problem, I made mistake in
line 9: I mistakenly had "res += to_string(strs[i].size()) + string(HEAD_SIZE-strs[i].size(), '.' + strs[i]". Note, the head size should be the size of the converted head size number.
line 17: I mistakenly had "i++" in the end.

1:  #define HEAD_SIZE 16  
2:  class Codec {  
3:  public:  
4:    // Encodes a list of strings to a single string.  
5:    string encode(vector<string>& strs) {  
6:      string res;  
7:      for (int i = 0; i < strs.size(); i++) {  
8:        string s = to_string(strs[i].size());  
9:        string append = string(HEAD_SIZE-s.size(), '.');  
10:        res += s + append + strs[i];  
11:      }  
12:      return res;  
13:    }  
14:    // Decodes a single string to a list of strings.  
15:    vector<string> decode(string s) {  
16:      vector<string> res;  
17:      for (int i = 0; i < s.size();) {  
18:        string head = s.substr(i, HEAD_SIZE);  
19:        int len = stol(head, NULL, 10);  
20:        i += HEAD_SIZE;  
21:        if (len > 0) res.push_back(s.substr(i, len));  
22:        else res.push_back("");  
23:        i += len;  
24:      }  
25:      return res;  
26:    }  
27:  };  
28:  // Your Codec object will be instantiated and called as such:  
29:  // Codec codec;  
30:  // codec.decode(codec.encode(strs));  

No comments:

Post a Comment