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.

Python:

class Codec:
def __init__(self):
self.__random_length = 6
self.__tiny_url = "http://tinyurl.com/"
self.__alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
self.__lookup = {} def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str
:rtype: str
"""
def getRand():
rand = []
for _ in xrange(self.__random_length):
rand += self.__alphabet[random.randint(0, len(self.__alphabet)-1)]
return "".join(rand) key = getRand()
while key in self.__lookup:
key = getRand()
self.__lookup[key] = longUrl
return self.__tiny_url + key def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL. :type shortUrl: str
:rtype: str
"""
return self.__lookup[shortUrl[len(self.__tiny_url):]]

Python:Using sha256

from hashlib import sha256

class Codec:

    def __init__(self):
self._cache = {}
self.url = 'http://tinyurl.com/' def encode(self, long_url):
"""Encodes a URL to a shortened URL.
:type long_url: str
:rtype: str
"""
key = sha256(long_url.encode()).hexdigest()[:6]
self._cache[key] = long_url
return self.url + key def decode(self, short_url):
"""Decodes a shortened URL to its original URL.
:type short_url: str
:rtype: str
"""
key = short_url.replace(self.url, '')
return self._cache[key]

C++:

class Solution {
public:
Solution() : gen_((random_device())()) {
} // Encodes a URL to a shortened URL.
string encode(string longUrl) {
string key = getRand();
while (lookup_.count(key)) {
key = getRand();
}
lookup_[key] = longUrl;
return "http://tinyurl.com/" + key;
} // Decodes a shortened URL to its original URL.
string decode(string shortUrl) {
return lookup_[shortUrl.substr(tiny_url.length())];
} private:
string getRand() {
string random;
for (int i = 0; i < random_length; ++i) {
random += alphabet_[uniform_int_distribution<int>{0, alphabet_.length() - 1}(gen_)];
}
return random;
} const int random_length = 6;
const string tiny_url = "http://tinyurl.com/";
const string alphabet_ = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
default_random_engine gen_;
unordered_map<string, string> lookup_;
};

  

类似题目:

[LeetCode] 534. Design TinyURL 设计短网址

All LeetCode Questions List 题目汇总

  

[LeetCode] 535. Encode and Decode TinyURL 编码和解码短网址的更多相关文章

  1. 535 Encode and Decode TinyURL 编码和解码精简URL地址

    详见:https://leetcode.com/problems/encode-and-decode-tinyurl/description/ C++: class Solution { public ...

  2. [LeetCode] Encode and Decode TinyURL 编码和解码精简URL地址

    Note: This is a companion problem to the System Design problem: Design TinyURL. TinyURL is a URL sho ...

  3. 535. Encode and Decode TinyURL - LeetCode

    Question 535. Encode and Decode TinyURL Solution 题目大意:实现长链接加密成短链接,短链接解密成长链接 思路:加密成短链接+key,将长链接按key保存 ...

  4. LC 535. Encode and Decode TinyURL

    Note: This is a companion problem to the System Design problem: Design TinyURL. TinyURL is a URL sho ...

  5. 【Leetcode】535. Encode and Decode TinyURL

    Question: TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/pro ...

  6. 【LeetCode】535. Encode and Decode TinyURL 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 解题方法 方法一:数组 方法二:字典 日期 题目地址:https://l ...

  7. 535. Encode and Decode TinyURL

    ▶ 要求给出一种对 URL 网址进行压缩和解压的算法,例如 https://leetcode.com/problems/design-tinyurl ←→ http://tinyurl.com/4e9 ...

  8. 535. Encode and Decode TinyURL 长短URL

    [抄题]: TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problem ...

  9. 535. Encode and Decode TinyURL(rand and srand)

    Note: This is a companion problem to the System Design problem: Design TinyURL. TinyURL is a URL sho ...

随机推荐

  1. 动态域名作为dga的做法

    https://wenku.baidu.com/view/54b1df373968011ca3009183.html dga算法 import time from ctypes import c_in ...

  2. windows(hexo)使用git时出现:warning: LF will be replaced by CRLF

    hexo出现warning: LF will be replaced by CRLF git config --global core.autocrlf false //禁用自动转换

  3. [CSS3] Use media query to split css files and Dark mode (prefers-color-scheme: dark)

    Dark Mode: :root { --text-color: #000; --background-color: #fff; } body { color: var(--text-color); ...

  4. 2019.12.09 java循环(do……while)

    class Demo05{ public static void main(String[] args) { int sum=0; int i=1; do{ sum+=i; i++; }while(i ...

  5. Gift to XBACK(小小礼物)

    什么白天 什么黑夜 我没有 准备着给你的 Surprise 你给我的爱 让我觉得已足够 是你让我相信爱会有 是你的爱陪我绕宇宙 打开日记本写下忧愁 你却让我看时间轴 我才知道现在我能看到的画面 拥有你 ...

  6. 【JZOJ6206】【20190610】二分图边染色

    题目 ​ 对一个二分图的边染色,满足有相同端点的边的颜色一定不同; ​ 设最优染色为\(C\) ,你的染色为\(X\),只需要满足$ X \le 2^ {\lceil log  C \rceil }$ ...

  7. 【后缀数组】【LuoguP2852】 [USACO06DEC]牛奶模式Milk Patterns

    题目链接 题目描述 农夫John发现他的奶牛产奶的质量一直在变动.经过细致的调查,他发现:虽然他不能预见明天产奶的质量,但连续的若干天的质量有很多重叠.我们称之为一个"模式". J ...

  8. Linux修改服务器Oracle字符集

    Linux安装Oracle时太仓促,没设置好,导入dmp字符集(ZHS16GBK)与服务器字符集(WE8MSWIN1252)对不上,导致导入数据失败: [oracle@ORACLE ~]$ sqlpl ...

  9. gulp/webpack运行sass报错解决方法

    帮同事安装gulp和webpack运行环境,使用cnpm install安装node-sass之后,运行项目总是报错,提示vendor目录不存在,几番百度之后,找到处理方法,这里记录一笔,防止以后遇到 ...

  10. 18年今日头条笔试第一题题解:球迷(fans)

    其实本题是加强版,原数据是100*100的,老师为了尊重我们的智商加成了3000*3000并进行了字符串处理…… 上原题~ 球迷 [问题描述] 一个球场C的球迷看台可容纳M*N个球迷.官方想统计一共有 ...