Leetcode:编码并解码短网址

题目要求

编写一个类,提供两个方法。一个可以将普通的网址编码成短网址,一个可以将短网址还原为普通网址。

参考题解

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# 使用随机函数,生成短网址,保存在dict中,避免重复
import random
import math
import re

class Codec:
charbase = [x for x in "0123456789abcdefghijklmnopqrstuvwxyz"]
urldict = {}
longurldict = {}

def get_random_char(self, length):
random_char = ""
#print(len(self.charbase))

for x in range(6):
random_char += self.charbase[math.ceil(random.random() * len(self.charbase) ) - 1 ]

return random_char

def encode(self, longUrl):
if longUrl in self.longurldict:
return self.longurldict[longUrl]

url_code = self.get_random_char(6)
if url_code in self.urldict:
self.encode(longUrl)
else:
self.longurldict[longUrl] = url_code
self.urldict[url_code] = longUrl

return "http://tinyurl.com/" + url_code

def decode(self, shortUrl):
domain = "http://tinyurl.com/"
shortUrl = shortUrl.replace(domain, "")

if shortUrl in self.urldict:
return self.urldict[shortUrl]
else:
return false

url = "https://leetcode.com/problems/design-tinyurl";
codec = Codec()
print(codec.get_random_char(6))
print(codec.get_random_char(6))
print(codec.get_random_char(6))
print(codec.get_random_char(6))
print(codec.get_random_char(6))

print(codec.encode(url))
print(codec.decode(codec.encode(url)))


我这个过程遇到一个坑,本地环境是Python3,math.ceil函数返回了整型数,Leetcode是Python2的环境,所以返回了浮点数,需要做一下类型转换。看了一下其他解题方法,其实可以直接用 hash 函数,不用考虑那么多。

cocowool

A FULL STACK DREAMER!