271. Encode and Decode Strings

class Codec {
public:

    // Encodes a list of strings to a single string.
    string encode(vector<string>& strs) {
        string res = "";
        for (auto& a : strs) {
            // 轉成size/字串size/字串size/字串
            // ["Hello","World"] -> 5/Hello5/World
            res.append(to_string(a.size())).append("/").append(a);
        }
        return res;
    }

    // Decodes a single string to a list of strings.
    vector<string> decode(string s) {
        vector<string> res;
        int i = 0;
        while (i < s.size()) {
            // 找到分隔號的位置
            auto found = s.find("/", i);

            // 得到字串長度
            int len = stoi(s.substr(i, found - i));

            // 將字串推到 array
            res.push_back(s.substr(found + 1, len));

            // 下一根指針
            i = found + len + 1;
        }
        return res;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.decode(codec.encode(strs));
  • T: O(N)O(N)
  • S: O(N)O(N)