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)))

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

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

时间: 2024-09-14 06:31:17

Leetcode刷题记录:编码并解码短网址的相关文章

Leetcode刷题记录:构建最大数二叉树

题目要求,题目地址 给定一个不含重复数字的数组,最大二叉树构建规则如下: 1.根是数组中最大的数字 2.左边的子树是最大数字左边的内容 3.右边的子树是最大数字右边的内容 答案 class Solution(object): def constructMaximumBinaryTree(self, nums): """ :type nums: List[int] :rtype: TreeNode """ #print(max(nums)) #pr

LeetCode刷题之一:寻找只出现一次的数字

投简历的时候看到了个刷题网站,http://www.nowcoder.com/527604,就做了一套题,现记录下来. 题目为: Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it withou

LeetCode 刷题之二:寻找二叉树的最大深度

题目为: Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 阶梯思路:对于这种题目最简单的方法就是递归操作了 代码为: /** * Definition for binary tree * public class TreeNod

LeetCode刷题之三:判断两个二叉树是否相同

题目为: Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 解题思路:这种题目也是递归操作简单 代码为: /** * Definition for binary tree * pub

c++问题-在acm上刷题老是通不过,求大神指点一二,到底问题出在哪里。不胜感激!!!

问题描述 在acm上刷题老是通不过,求大神指点一二,到底问题出在哪里.不胜感激!!! #include #include using namespace std; int main() { int T; int k,t=0; int i, j, n1, n2; char a[1010], b[1010], c[1015]; string d[20], e[20], f[20]; cin>>T; for(k=1; k<=T; k++) { cin>>a>>b; d[

base64编码、解码函数

编码|函数 这是我看完几个base64编码.解码函数后自己改写的.因为,在中文操作系统的VBscript中,使用的是unicode字符集,所以很多base64编码.解码函数在理论上是正确的,但实际不能运行! 我加写了几个Unicode与Ansi编码转换的函数,现贴出来,请大家执教! 文件名称base64test.asp <% sBASE_64_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567

PHP中的UNICODE 编码与解码

本篇文章是对PHP中的UNICODE 编码与解码进行了详细的分析介绍,需要的朋友参考下   方法一: 复制代码 代码如下: <?php function unicode_encode($name) { $name = iconv('UTF-8', 'UCS-2', $name); $len = strlen($name); $str = ''; for ($i = 0; $i < $len - 1; $i = $i + 2) { $c = $name[$i]; $c2 = $name[$i +

javascript中的Base64、UTF8编码与解码详解

 本文给大家介绍的是javascript中的Base64.UTF8编码与解码的函数源码分享以及使用范例,十分实用,推荐给小伙伴们,希望大家能够喜欢.     Base64编码说明 Base64编码要求把3个8位字节(3*8=24)转化为4个6位的字节(4*6=24),之后在6位的前面补两个0,形成8位一个字节的形式. 如果剩下的字符不足3个字节,则用0填充,输出字符使用'=',因此编码后输出的文本末尾可能会出现1或2个'='. base64编码库:(已验证可用)   代码如下: var base

数据存储-sql server在同一表中筛选出两次刷卡记录时间大于等于40分钟的员工数据

问题描述 sql server在同一表中筛选出两次刷卡记录时间大于等于40分钟的员工数据 刷卡进出数据存储在同一表中,姓名有重复的,一个人可能刷了2次,要求选出在时间段2014-12-28 11:00:00到2014-12-28 13:00:00内两次刷卡记录时间间隔大于等于40分钟的员工 logtime (时间 )logcard (卡号 )logid () logname(姓名) logbm (部门) 解决方案 ```select * from 同一表 a where logtime betw