535.tiny-url-的加密与解密
/*
* @lc app=leetcode.cn id=535 lang=typescript
*
* [535] TinyURL 的加密与解密
*/
// @lc code=start
/**
* Encodes a URL to a shortened URL.
*/
function encode(longUrl: string): string {}
/**
* Decodes a shortened URL to its original URL.
*/
function decode(shortUrl: string): string {}
/**
* Your functions will be called as such:
* decode(encode(strs));
*/
// @lc code=end
const map = new Map<string, string>()
const chs: string[] = []
for (let i = 0; i < 26; i++) chs.push(String.fromCharCode(i + 65))
for (let i = 0; i < 26; i++) chs.push(String.fromCharCode(i + 97))
for (let i = 0; i < 10; i++) chs.push(i + '')
const random = () => {
const res: string[] = []
for (let i = 0; i < 10; i++) {
const ch = chs[Math.floor(Math.random() * chs.length)]
res.push(ch)
}
return res.join('')
}
function encode(longUrl: string): string {
let str = random()
while (map.has(str)) str = random()
map.set(str, longUrl)
return str
}
function decode(shortUrl: string): string {
return map.get(shortUrl)!
}