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
Design the
Analysis[/i]
编码部分,使用字符串hash函数,将longUrl哈希获得
解码部分,截取
代码:
Description[/i]
TinyURL is a URL shortening service where you enter a URL such as
https://leetcode.com/problems/design-tinyurland it returns a short URL such as
http://tinyurl.com/4e9iAk.
Design the
encodeand
decodemethods 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; };
相关文章推荐
- LeetCode:535. Encode and Decode TinyURL
- leetcode535 Encode and Decode TinyURL java
- leetcode 535. Encode and Decode TinyURL
- 20170613-leetcode-535-Encode and Decode TinyURL
- LeetCode 535. Encode and Decode TinyURL对随机编码的思考
- 【LeetCode】535. Encode and Decode TinyURL
- LeetCode 535 Encode and Decode TinyURL (HashMap)
- 【LeetCode】535. Encode and Decode TinyURL
- Leetcode 535 Encode and Decode TinyURL
- LeetCode Encode and Decode TinyURL
- leetcode题解-535. Encode and Decode TinyURL
- LeetCode 535: Encode and Decode TinyURL
- [LeetCode] Encode and Decode TinyURL 编码和解码精简URL地址
- python--leetcode 535. Encode and Decode TinyURL
- Leetcode: Encode and Decode TinyURL
- lintcode/leetcode由易至难第21题:Encode and Decode TinyURL
- Leetcode刷题之路(Python)——535. Encode and Decode TinyURL
- LeetCode - Encode And Decode TinyURL
- leetcode 535. Encode and Decode TinyURL
- Leetcode 535. Encode and Decode TinyURL