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;};
阅读全文
0 0
- LeetCode-Encode and Decode TinyURL
- leetcode题解-535. Encode and Decode TinyURL
- 【LeetCode】535. Encode and Decode TinyURL
- LeetCode:535. Encode and Decode TinyURL
- Leetcode 535. Encode and Decode TinyURL
- leetcode 535. Encode and Decode TinyURL
- Leetcode 535. Encode and Decode TinyURL
- 20170613-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】535. Encode and Decode TinyURL
- python--leetcode 535. Encode and Decode TinyURL
- leetcode 535. Encode and Decode TinyURL
- Encode and Decode TinyURL
- Encode and Decode TinyURL
- Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- matplotlib库的简单使用(入门)
- Java-类
- Ubuntu16.04-x64安装caffe2(仅CPU)
- 访问者模式。
- 字符编码笔记汇总:ASCII、GBXXXX、Unicode、UTF-8等
- LeetCode-Encode and Decode TinyURL
- Python函数--numpy.fromfunction( )
- 设计模式 -- 结构型模式
- 震惊,登入P站的post_key竟然在!!!
- 237. Delete Node in a Linked List。
- 【csf-201312-2】ISBN号码
- 纯css实现的流星雨的效果
- tomcat web.xml文件加载
- python 写socket—文件上传下载