您的位置:首页 > 其它

LeetCode-Encode and Decode TinyURL

2017-09-16 21:07 537 查看
1. Encode and Decode TinyURL(Medium)

Description[/i]

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[/i]

编码部分,使用字符串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;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法