[Leetcode] 535. Encode and Decode TinyURL 解题报告

来源:互联网 发布:垃圾邮件分类算法 编辑:程序博客网 时间:2024/05/22 16:13

题目

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.

思路

目测这道题目应该有多种不同的解法,这里给出其中的一种。维护一个全局的id,每次遇到新的longUrl,就给它赋一个新的id。现在问题就是如何把id映射为一个shortUrl了。我们采用的做法是:把这个shortUrl看作是一个“62进制”的数,其基由10个数字加上26个小写字母以及26个大写字母组成。这样问题就转化为10进制的id和62进制的shortUrl了(用string表示)之间的转换了。

encode:遇到一个新的longUrl后,我们赋给它一个新的id,然后将这个10进制的id转换为62进制的shortUrl,并且建立longUrl到shortUrl之间的哈希映射,以及id到longUrl之间的映射,以便于decode的时候使用。

decode:遇到一个shortUrl之后,我们将它转换为10进制的id,然后在哈希表中查找,返回对应的longUrl即可。

当然也可以直接建立shortUrl到longUrl之间的映射,而不是id到longUrl之间的映射。这样在decode的时候,就不需要进行进制之间的转换了。读者可以试着实现一下。

代码

class Solution {public:    // Encodes a URL to a shortened URL.    string encode(string longUrl) {        if(long_short.find(longUrl) != long_short.end()) {            return long_short[longUrl];        }        string res = "";        id++;        int count = id;        while(count > 0) {            res = dict[count % 62] + res;            count /= 62;        }        while(res.size() < 6) {            res = "0" + res;        }        long_short[longUrl] = res;        id_long[id] = longUrl;        return res;    }    // Decodes a shortened URL to its original URL.    string decode(string shortUrl) {        int id = 0;        for(int i = 0; i < shortUrl.size(); i++) {            id = 62 * id + (int)(dict.find(shortUrl[i]));        }        if(id_long.find(id) != id_long.end()) {            return id_long[id];        }        return "";    }private:    string dict = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";    int id = 0;    unordered_map<string,string> long_short;    // key is longURL, value is shortURL    unordered_map<int, string> id_long;         // key is id in DB, value is longURL};// Your Solution object will be instantiated and called as such:// Solution solution;// solution.decode(solution.encode(url));