python--leetcode 535. Encode and Decode TinyURL
来源:互联网 发布:人工智能教学百度云 编辑:程序博客网 时间:2024/05/18 03:51
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.
这一题还是比较有意思的,题目意思就是说输入一个网址,让你用算法缩短这个网址,而且能否复原原网址。
当然这一题可以耍点小聪明就过了,直接return longurl 和return shorturl返回原地址。不过这并非我们刷leetcode的本意。
下面上代码,我一会再解释代码的意思:
class Codec: import string letters = string.ascii_letters + string.digits #abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 full_tiny = {} tiny_full = {} global_counter = 0 def encode(self, longUrl): """Encodes a URL to a shortened URL. :type longUrl: str :rtype: str """ def decto62(dec): ans = "" while 1: ans = self.letters[dec % 62] + ans dec //= 62 if not dec: break print('ans:',ans) return ans suffix = decto62(self.global_counter) if longUrl not in self.full_tiny: self.full_tiny[longUrl] = suffix self.tiny_full[suffix] = longUrl self.global_counter += 1 return "http://tinyurl.com/" + suffix def decode(self, shortUrl): """Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str """ idx = shortUrl.split('/')[-1] print('fulltiny',self.full_tiny,self.tiny_full) if idx in self.tiny_full: return self.tiny_full[idx] else: return Nonecodec = Codec()url='fffffffffff'print(codec.decode(codec.encode(url)))这里会输出以下内容:
ans: a
fulltiny {'fffffffffff': 'a'} {'a': 'fffffffffff'}
fffffffffff
解题思路:将输入的长地址与生成的短地址通过字典一一对应。dector62方法就是生成短地址的方法,通过global_counter的递增并取余,来获得短地址。
- python--leetcode 535. Encode and Decode TinyURL
- leetcode题解-535. Encode and Decode TinyURL
- 【LeetCode】535. Encode and Decode TinyURL
- LeetCode:535. Encode and Decode TinyURL
- Leetcode 535. Encode and Decode TinyURL
- leetcode 535. Encode and Decode TinyURL
- Leetcode 535. Encode and Decode TinyURL
- LeetCode 535. Encode and Decode TinyURL
- 【LeetCode】535. Encode and Decode TinyURL
- leetcode 535. Encode and Decode TinyURL
- LeetCode-Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- 子元素浮动后,两个子元素高度不一样,父元素自适应高度,子元素自适应为相同高度
- 手把手教你写二叉查找树Binary Search Tree(1)
- iOS11人机交互指南-01 iPhone X概览
- 身份认证加salt
- Activity的四种启动模式讲解
- python--leetcode 535. Encode and Decode TinyURL
- [Haskell] CodeWars|Find the middle element
- [leetcode] House Robber [i ii iii]
- C# winform之属性 bindingNavigator
- bzoj1345(区间合并式的贪心)
- windows下nginx的安装及使用方法入门
- Codeforces Round #302 (Div. 2) D
- 669. Trim a Binary Search Tree Difficulty : Easy
- Linux创建ftp并设置权限以及忘记ftp帐号(密码)修改