# 271 - Encode and Decode Strings

解法一 - 加上 每個 string length & delimiter

我們 encode 重點是要能夠區分出每個 string,但問題在於,string 中可以有所有的 ASCII char,所以不管用什麼 char 當作區分的 char,都不能 work。所以我們可以加上一個數字,數字後面就跟著 delimiter,這樣就不會出錯。

舉例來說,如果 strs 裡面有 "h/aabb", "j/e",我們會 encode 成:6/h/aabb3/j/e。當我們讀到 6,就知道從接著的 / 後要讀 6 個 char,所以會讀到 h/aabb,這樣就不會被 h/aabb 裡面的 / 干擾。

class Codec {
public:

    // Encodes a list of strings to a single string.
    string encode(vector<string>& strs) {
        string encoded_string;

        for(auto& str: strs) {
            encoded_string += to_string(str.length()) + "/" + str;
        }

        return encoded_string;
    }

    // Decodes a single string to a list of strings.
    vector<string> decode(string s) {
        vector<string> res;

        int i = 0;
        while(i < s.size()) {
            int slash = s.find("/", i);
            int length = stoi( s.substr(i, slash-i) );
            res.push_back( s.substr(slash+1, length) );
            i = slash + 1 + length; 
        }

        return res;
    }
};

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

Last updated