Advertisement
nikunjsoni

271

Jun 27th, 2021
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 KB | None | 0 0
  1. class Codec {
  2. public:
  3.  
  4.     // Encodes a list of strings to a single string.
  5.     string encode(vector<string>& strs) {
  6.         string encoded = "";
  7.         for (string &str: strs) {
  8.             int len = str.size();
  9.             encoded += to_string(len) + "@" + str;
  10.         }
  11.         return encoded;
  12.     }
  13.  
  14.     // Decodes a single string to a list of strings.
  15.     vector<string> decode(string s) {
  16.         vector<string> r;
  17.         int head = 0;
  18.         while(head < s.size()) {
  19.             int at_pos = s.find('@', head);
  20.             int len = stoi(s.substr(head, at_pos - head));
  21.             head = at_pos + 1;
  22.             r.push_back(s.substr(head, len));
  23.             head += len;
  24.         }
  25.         return r;
  26.     }
  27. };
  28.  
  29.  
  30. // Your Codec object will be instantiated and called as such:
  31. // Codec codec;
  32. // codec.decode(codec.encode(strs));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement