535. Encode and Decode TinyURL

来源:互联网 发布:linux make安装包下载 编辑:程序博客网 时间:2024/06/08 06:29

题目

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的编码算法与解码算法。于是乎,很多人直接return了。如下所示:

class Solution {public:    // Encodes a URL to a shortened URL.    string encode(string longUrl) {        return longUrl;    }    // Decodes a shortened URL to its original URL.    string decode(string shortUrl) {        return shortUrl;    }};// Your Solution object will be instantiated and called as such:// Solution solution;// solution.decode(solution.encode(url));

上述两行代码号称最佳解决方案。但是咱们肯定不能这样做,那么这道题目的初衷又是什么呢?其实本质上,这道题目是一道关于哈希映射的题目,本质上是为了做url的函数表达。我们来分析下编码与解码的具体思路。
这道题目希望你把形如:https://leetcode.com/problems/design-tinyurl 的url链接,编码成前缀为:http://tinyurl.com/ +字符串的格式。
那么我们首先想到的是C++ STL中有个hash函数,可以将任意字符串hash成一个整数。那么我们可以建立两个unorder_map函数,其中一个函数存储longUrl与shortUrl的映射关系,另一个函数存储shortUrl与longUrl之间的映射关系。
但是这样是不够的,我们还要考虑在每次做hash时,原存储容器中是否已经存在某相同url了,如果存在我们就不做重复的hash操作。

代码

class Solution {public:    unordered_map<string,string> longmap;    unordered_map<string,string> tinymap;    string prefix = "http://tinyurl.com/";    // Encodes a URL to a shortened URL.    string encode(string longUrl) {        if (longmap.find(longUrl) != longmap.end())            ;        else        {              hash<string> hash_fn;            longmap[longUrl] = prefix + to_string(hash_fn(longUrl));            tinymap[longmap[longUrl]] = longUrl;        }           return longmap[longUrl];    }    // Decodes a shortened URL to its original URL.    string decode(string shortUrl) {        return tinymap[shortUrl];    }};// Your Solution object will be instantiated and called as such:// Solution solution;// solution.decode(solution.encode(url));
原创粉丝点击