# Leetcode刷题记录：编码并解码短网址

+关注继续查看

### 参考题解

# 使用随机函数，生成短网址，保存在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)))


LeetCode 394. 字符串解码
LeetCode 394. 字符串解码
8 0
LeetCode 394. 字符串解码

16 0
LeetCode 820. 单词的压缩编码 Short Encoding of Words
LeetCode 820. 单词的压缩编码 Short Encoding of Words
9 0
Leetcode 1313. 解压缩编码列表
Leetcode 1313. 解压缩编码列表
15 0
LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之二：编码实现

39 0
☆打卡算法☆LeetCode 89、格雷编码 算法解析
“给定一个整数，返回任一有效的n位格雷码序列。”
74 0
​LeetCode刷题实战393：UTF-8 编码验证

78 0

38 0
+关注