【LeetCode】【Math】encode and decode tinyURL 如何将一个长URL转换为一个短URL
题目:
注意:这是系统设计问题的伴随问题:设计TinyURL。TinyURL是URL缩短服务,您可以在其中输入URL,例如https://leetcode.com/problems/design-tinyurl,并返回短URL,例如http://tinyurl.com/4e9iAk。
设计TinyURL服务的编码和解码方法。 编码/解码算法的工作方式没有限制。 您只需要确保可以将URL编码为小URL,并且可以将小URL解码为原始URL。
【解法】
class Codec: def __init__(self): self.urls = [] def encode(self, longUrl:str) -> str: self.urls.append(longUrl) return 'http://tinyurl.com/' + str(len(self.urls) - 1) def decode(self, shortUrl:str) -> str: return self.urls[int(shortUrl.split('/')[-1])] # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.decode(codec.encode(url))
Runtime: 52 ms, faster than 12.06% of Python3 online submissions for Encode and Decode TinyURL.
Memory Usage: 13.8 MB, less than 66.61% of Python3 online submissions for Encode and Decode TinyURL.
短网址
顾名思义,就是将长网址缩短到一个很短的网址,用户访问这个短网址可以重定向到原本的长网址(也就是还原的过程)。这样可以达到易于记忆、转换、节省长度的目的,常用于有字数限制的微博、二维码等等场景。
如何生成短地址URL
通过发号策略,给每一个过来的长地址发一个号。小型系统可以直接用mysql的自增索引,大型应用可以考虑各种分布式key-value系统做发号器。第一个服务短地址是xx.xx/0,是xx.xx/1,第n个xx.xx/n。
开源项目
urlshorter本身还是基于随机的方式生成短地址的,并不算是一个短地址发号器,因此会有性能问题和冲突的出现,
原文链接:https://blog.csdn.net/xlgen157387/java/article/details/80026452

浙公网安备 33010602011771号