Leetcode 271 Solution

This article provides solution to leetcode question 271 (encode-and-decode-strings)

https://leetcode.com/problems/encode-and-decode-strings

Solution

class Codec { public:
// Encodes a list of strings to a single string. string encode(vector<string>& strs) { string res; for (auto str : strs) { res += to_string(str.size()); res += "/"; res += str; } return res; }
// Decodes a single string to a list of strings. vector<string> decode(string s) { int i = 0;
vector<string> res; while (i < s.size()) { int j = s.find_first_of("/", i); if (j == string::npos) break; string len = s.substr(i, j - i); int ilen = atoi(len.c_str()); res.push_back(s.substr(j + 1, ilen)); i = j + 1 + ilen; } return res; } };
// Your Codec object will be instantiated and called as such: // Codec codec; // codec.decode(codec.encode(strs));