[LeetCode] 535. Encode and Decode TinyURL 编码和解码短网址
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 编码和解码短网址的更多相关文章
- 535 Encode and Decode TinyURL 编码和解码精简URL地址
详见:https://leetcode.com/problems/encode-and-decode-tinyurl/description/ C++: class Solution { public ...
- [LeetCode] Encode and Decode TinyURL 编码和解码精简URL地址
Note: This is a companion problem to the System Design problem: Design TinyURL. TinyURL is a URL sho ...
- 535. Encode and Decode TinyURL - LeetCode
Question 535. Encode and Decode TinyURL Solution 题目大意:实现长链接加密成短链接,短链接解密成长链接 思路:加密成短链接+key,将长链接按key保存 ...
- LC 535. Encode and Decode TinyURL
Note: This is a companion problem to the System Design problem: Design TinyURL. TinyURL is a URL sho ...
- 【Leetcode】535. Encode and Decode TinyURL
Question: TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/pro ...
- 【LeetCode】535. Encode and Decode TinyURL 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 解题方法 方法一:数组 方法二:字典 日期 题目地址:https://l ...
- 535. Encode and Decode TinyURL
▶ 要求给出一种对 URL 网址进行压缩和解压的算法,例如 https://leetcode.com/problems/design-tinyurl ←→ http://tinyurl.com/4e9 ...
- 535. Encode and Decode TinyURL 长短URL
[抄题]: TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problem ...
- 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 ...
随机推荐
- js中的全局对象
- Djiango-建立模型抽象基类
创建一个抽象模型基类 ‘ 然后 ’base_model.py from django.db import models from datetime import date class BaseMode ...
- hibernate笔记
1.hibernate中的list()遍历方法和iterator()遍历方法之间的区别 1:返回的类型不一样,list()返回List, iterate()返回Iterator,2: 获取数据的方式不 ...
- 修改Tomcat启动窗口的名称(Title)
内容简介 有时在运行项目时,在同一服务器会启动多个Tomcat,很难区分某个tomcat运行的是哪个项目,或者想查看tomcat的端口号,只能去server.xml中查看. 如果能把Tomcat窗口的 ...
- 51nod1463 找朋友
[传送门] 写的时候一直没有想到离线解法,反而想到两个比较有趣的解法.一是分块,$f[i][j]$表示第$i$块块首元素到第$j$个元素之间满足条件的最大值(即对$B_l + B_r \in K$的$ ...
- Linux cp/rm/mv 强制覆盖
一.Linux下的cp/rm/mv强制覆盖 (一).反斜杠(\)临时取消别名 [root@fz ~]# \cp filename new/filename [root@fz ~]# (二).unali ...
- 使用window.localStorage,window.localStorage记录点击次数
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- asp.net web开发——文件的上传和下载
HTML部分 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.a ...
- 洛谷P2730 [IOI]魔板 Magic Squares
题目背景 在成功地发明了魔方之后,鲁比克先生发明了它的二维版本,称作魔板.这是一张有8个大小相同的格子的魔板: 1 2 3 4 8 7 6 5 题目描述 我们知道魔板的每一个方格都有一种颜色.这8种颜 ...
- mysql 创建分组
mysql> select * from table1; +----------+------------+-----+---------------------+ | name_new | t ...