1. 程式人生 > >[LeetCode] Encode and Decode Strings 加碼解碼字串

[LeetCode] Encode and Decode Strings 加碼解碼字串

Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.

Machine 1 (sender) has the function:

string encode(vector<string> strs) {
  // ... your code
  return encoded_string;
}

Machine 2 (receiver) has the function:

vector<string> decode(string s) {
  //... your code
  return strs;
}

So Machine 1 does:

string encoded_string = encode(strs);

and Machine 2 does:

vector<string> strs2 = decode(encoded_string);

strs2 in Machine 2 should be the same as strs in Machine 1.

Implement the encode

 and decode methods.

Note:

  • The string may contain any possible characters out of 256 valid ascii characters. Your algorithm should be generalized enough to work on any possible characters.
  • Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.
  • Do not rely on any library method such as eval or serialize methods. You should implement your own encode/decode algorithm.

這道題讓我們給字元加碼再解碼,先有碼再無碼,然後題目中並沒有限制我們加碼的方法,那麼我們的方法只要能成功的把有碼變成無碼就行了,具體變換方法我們自己設計。由於我們需要把一個字串集變成一個字串,然後把這個字串再還原成原來的字串集,最開始我想能不能在每一個字串中間加個空格把它們連起來,然後再按空格來隔開,但是這種方法的問題是原來的一個字串中如果含有空格,那麼還原的時候就會被分隔成兩個字串,所以我們必須還要加上長度的資訊,我們的加碼方法是長度+"/"+字串,比如對於"a","ab","abc",我們就變成"1/a2/ab3/abc",那麼我們解碼的時候就有規律可尋,先尋找"/",然後之前的就是要取出的字元個數,從“/"後取出相應個數即可,以此類推直至沒有"/"了,這樣我們就得到高清無碼的字串集了,參見程式碼如下:

解法一:

class Codec {
public:
    // Encodes a list of strings to a single string.
    string encode(vector<string>& strs) {
        string res = "";
        for (auto a : strs) {
            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 = atoi(s.substr(i, found).c_str());
            res.push_back(s.substr(found + 1, len));
            i = found + len + 1;
        }
        return res;
    }
};

上面的方法是用一個變數i來記錄當前遍歷到的位置,我們也可以通過修改修改s,將已經解碼的字串刪掉,最終s變為空的時候停止迴圈,參見程式碼如下:

解法二:

class Codec {
public:
    // Encodes a list of strings to a single string.
    string encode(vector<string>& strs) {
        string res = "";
        for (auto a : strs) {
            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;
        while (!s.empty()) {
            int found = s.find("/");
            int len = atoi(s.substr(0, found).c_str());
            s = s.substr(found + 1);
            res.push_back(s.substr(0, len));
            s = s.substr(len);
        }
        return res;
    }
};

參考資料: