开发者社区> 大江小浪> 正文

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

简介: 题目要求 编写一个类,提供两个方法。一个可以将普通的网址编码成短网址,一个可以将短网址还原为普通网址。 参考题解 # 使用随机函数,生成短网址,保存在dict中,避免重复 import random import math import re class Codec: charbase =...
+关注继续查看

题目要求

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

参考题解

# 使用随机函数,生成短网址,保存在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 函数,不用考虑那么多。

本文为作者原创,如果您觉得本文对您有帮助,请随意打赏,您的支持将鼓励我继续创作。

img_5aa33392af8827039c3ea963be129769.png

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
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)三部曲之二:编码实现
本文是《LeetCode第三题(Longest Substring Without Repeating Characters)三部曲》的第二篇,前一篇文章已经列出了完整的解题思路,今天来将此思路转化为具体的Java代码
39 0
☆打卡算法☆LeetCode 89、格雷编码 算法解析
“给定一个整数,返回任一有效的n位格雷码序列。”
74 0
​LeetCode刷题实战393:UTF-8 编码验证
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
78 0
代码随想录刷题|LeetCode 503.下一个更大元素II 42. 接雨水 84.柱状图中最大的矩形
代码随想录刷题|LeetCode 503.下一个更大元素II 42. 接雨水 84.柱状图中最大的矩形
38 0
+关注
大江小浪
平心静气,破浪劈坚!
文章
问答
文章排行榜
最热
最新
相关电子书
更多
低代码开发师(初级)实战教程
立即下载
阿里巴巴DevOps 最佳实践手册
立即下载
冬季实战营第三期:MySQL数据库进阶实战
立即下载