1. 程式人生 > >[LeetCode] Encode and Decode TinyURL 編碼和解碼精簡URL地址

[LeetCode] Encode and Decode TinyURL 編碼和解碼精簡URL地址

Note: This is a companion problem to the System Design problem: Design TinyURL.

TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk.

Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.

這道題讓我們編碼和解碼精簡URL地址,這其實很有用,因為有的連結地址特別的長,就很煩,如果能精簡成固定的長度,就很清爽。最簡單的一種編碼就是用個計數器,當前是第幾個存入的url就編碼成幾,然後解碼的時候也能根據數字來找到原來的url,參見程式碼如下:

解法一:

class Solution {
public:

    // Encodes a URL to a shortened URL.
    string encode(string longUrl) {
        url.push_back(longUrl);
        return "http://tinyurl.com/
" + to_string(url.size() - 1); } // Decodes a shortened URL to its original URL. string decode(string shortUrl) { auto pos = shortUrl.find_last_of("/"); return url[stoi(shortUrl.substr(pos + 1))]; } private: vector<string> url; };

上面這種方法雖然簡單,但是缺點卻很多,首先,如果接受到多次同一url地址,仍然會當做不同的url來處理。當然這個缺點可以通過將vector換成雜湊表,每次先查詢url是否已經存在。雖然這個缺點可以克服掉,但是由於是用計數器編碼,那麼當前伺服器存了多少url就曝露出來了,也許會有安全隱患。而且計數器編碼另一個缺點就是數字會不斷的增大,那麼編碼的長度也就不是確定的了。而題目中明確推薦了使用六位隨機字元來編碼,那麼我們只要在所有大小寫字母和數字中隨機產生6個字元就可以了,我們用雜湊表建立6位字元和url之間的對映,如果隨機生成的字元之前已經存在了,我們就繼續隨機生成新的字串,直到生成了之前沒有的字串為止。下面的程式碼中使用了兩個雜湊表,目的是為了建立六位隨機字串和url之間的相互對映,這樣進來大量的相同url時,就不用生成新的隨機字串了。當然,不加這個功能也能通過OJ,這道題的OJ基本上是形同虛設,兩個函式分別直接返回引數字串也能通過OJ,囧~

解法二:

class Solution {
public:
    Solution() {
        dict = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        short2long.clear();
        long2short.clear();
        srand(time(NULL));
    }

    // Encodes a URL to a shortened URL.
    string encode(string longUrl) {
        if (long2short.count(longUrl)) {
            return "http://tinyurl.com/" + long2short[longUrl];
        }
        int idx = 0;
        string randStr;
        for (int i = 0; i < 6; ++i) randStr.push_back(dict[rand() % 62]);
        while (short2long.count(randStr)) {
            randStr[idx] = dict[rand() % 62];
            idx = (idx + 1) % 5;
        }
        short2long[randStr] = longUrl;
        long2short[longUrl] = randStr;
        return "http://tinyurl.com/" + randStr;
    }

    // Decodes a shortened URL to its original URL.
    string decode(string shortUrl) {
        string randStr = shortUrl.substr(shortUrl.find_last_of("/") + 1);
        return short2long.count(randStr) ? short2long[randStr] : shortUrl;
    }
    
private:
    unordered_map<string, string> short2long, long2short;
    string dict;
};

參考資料: