LeetCode-Encode and Decode TinyURL

来源:互联网 发布:linux qt开发环境搭建 编辑:程序博客网 时间:2024/05/18 03:55

1. Encode and Decode TinyURL(Medium)

Description
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.

Analysis
编码部分,使用字符串hash函数,将longUrl哈希获得size_t 类型的值,将size_t值hash转换为字符串str,然后将该字符串和longUrl放入map <string, string> url中,返回"http://tinyurl.com/" + str
解码部分,截取shortUrl的后一部分,将其作为key来获取url中的对应长地址。

代码:

class Solution {public:    // Encodes a URL to a shortened URL.    string encode(string longUrl) {        size_t hash = hash_fn(longUrl);        string str = to_string(hash);        url.insert(map<string , string>::value_type(str, longUrl));        return "http://tinyurl.com/" + str;    }    // Decodes a shortened URL to its original URL.    string decode(string shortUrl) {        auto pos = shortUrl.find_last_of("/");        return url[shortUrl.substr(pos + 1)];    }private:    map <string, string> url;    std::hash<std::string> hash_fn;};