分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

leetcode-535. TinyURL 的加密与解密

发布时间:2023-09-06 02:10责任编辑:赖小花关键词:暂无标签

TinyURL是一种URL简化服务, 比如:当你输入一个URL https://leetcode.com/problems/design-tinyurl 时,它将返回一个简化的URL http://tinyurl.com/4e9iAk.

要求:设计一个 TinyURL 的加密 encode 和解密 decode 的方法。你的加密和解密算法如何设计和运作是没有限制的,你只需要保证一个URL可以被加密成一个TinyURL,并且这个TinyURL可以用解密方法恢复成原本的URL。

思路:

  首先读懂题意,从更高层次看,我们要做的是将长url(长字符串)映射为短url(短字符串)。

  首先想到的可能是找到某种映射关系,将长url映射为短url,但难度有点大。

  换一种思考的方式,我们对每个长url随机生成没有映射长url的短字符串,并记录下长短url之间映射关系,然后在解码的时候去查表即可。

代码:

import randomclass Codec: ???def __init__(self): ???????self.code = ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ‘ ???????self.long_to_short = {} ???????self.short_to_long = {} ???def encode(self, longUrl): ???????"""Encodes a URL to a shortened URL. ???????:type longUrl: str ???????:rtype: str ???????""" ???????if longUrl in self.long_to_short.keys(): ???????????return self.long_to_short.get(longUrl) ???????else: ???????????encode = self.encodeUrl() ???????????while encode in self.short_to_long.keys(): ???????????????encode = self.encodeUrl() ???????????self.long_to_short[longUrl] = encode ???????????self.short_to_long[encode] = longUrl ???????return encode ???def decode(self, shortUrl): ???????"""Decodes a shortened URL to its original URL. ???????:type shortUrl: str ???????:rtype: str ???????""" ???????return self.short_to_long.get(shortUrl) if shortUrl in self.short_to_long.keys() else ‘‘ ???????# Your Codec object will be instantiated and called as such: ???????# codec = Codec() ???????# codec.decode(codec.encode(url)) ???def encodeUrl(self): ???????return ‘‘.join([random.choice(self.code) for _ in range(6)])if __name__ == ‘__main__‘: ???codec = Codec() ???print(codec.decode(codec.encode("https://leetcode.com/problems/design-tinyurl")))

leetcode-535. TinyURL 的加密与解密

原文地址:https://www.cnblogs.com/namedlxd/p/9502430.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved