「每日LeetCode」2021年10月27日

本文最后更新于:2023年3月19日 晚上

Lt535. TinyURL 的加密与解密

535. TinyURL 的加密与解密

TinyURL 是一种 URL 简化服务, 比如:当你输入一个 URL https://leetcode.com/problems/design-tinyurl 时,它将返回一个简化的 URL http://tinyurl.com/4e9iAk.
要求:设计一个 TinyURL 的加密 encode 和解密 decode 的方法。你的加密和解密算法如何设计和运作是没有限制的,你只需要保证一个 URL 可以被加密成一个 TinyURL,并且这个 TinyURL 可以用解密方法恢复成原本的 URL。

思路

设计题,通过一个随机生成函数生成随机 6 位字符串,再通过 map 存储对应关系。

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
const map = {};

const generateStr = (length) => {
const dictionary =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
return new Array(length)
.fill("")
.map((e) => dictionary[parseInt(Math.random() * dictionary.length)])
.join("");
};

/**
* Encodes a URL to a shortened URL.
*
* @param {string} longUrl
* @return {string}
*/
const encode = function (longUrl) {
const str = generateStr(6);
const short = `http://tinyurl.com/${str}`;
map[short] = longUrl;
return short;
};

/**
* Decodes a shortened URL to its original URL.
*
* @param {string} shortUrl
* @return {string}
*/
const decode = function (shortUrl) {
return map[shortUrl];
};

/**
* Your functions will be called as such:
* decode(encode(url));
*/