分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

Encode and Decode TinyURL

发布时间:2023-09-06 01:28责任编辑:赖小花关键词:暂无标签

Encode and Decode TinyURL

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.

想了下可能的重复编码问题,直接用HashMap做了短URL和长URL的映射.将数字和字母混合编码,按题目的6位数的编码的话可以达到\(36^6\)种编码,理论上性能是ok的.
代码如下

public class Codec { ???HashMap<String, String> enIndex = new HashMap<String, String>(); ???HashMap<String,String>deIndex = new HashMap<String, String>(); ???String keyset = "0123456789abcdefghijklmnopqrstuvwyz"; ???String tinyUrlBase = "http://tinyurl.com/"; ???// Encodes a URL to a shortened URL. ???public String encode(String longUrl) { ???????String key; ???????if (enIndex.containsKey(longUrl)) return enIndex.get(longUrl); ???????do{ ???????????StringBuilder sb = new StringBuilder(); ???????????for(int i =0 ; i<6;i++){ ???????????????sb.append(keyset.charAt((int) (Math.random()*keyset.length()))); ???????????} ???????????key = sb.toString(); ???????}while(deIndex.containsKey(key)); ???????deIndex.put(key,longUrl); ???????enIndex.put(longUrl, tinyUrlBase+key); ???????return tinyUrlBase+key; ???} ???// Decodes a shortened URL to its original URL. ???public String decode(String shortUrl) { ???????return deIndex.get(shortUrl.replace(tinyUrlBase,"")); ???}}

写完看了下排名.....貌似蛮低的.不过这题感觉是比较自由,应该不会太卡时间的,感觉就是考虑怎么编码好点.
前面的方案大致有:

  1. 用计数器编码
    那么当前服务器存了多少url就曝露出来了,也许会有安全隐患。而且计数器编码另一个缺点就是数字会不断的增大
  2. 直接返回参数(最快)
    ....这道题的OJ基本上是形同虚设,两个函数分别直接返回参数字符串也能通过OJ,囧

Encode and Decode TinyURL

原文地址:http://www.cnblogs.com/Dyleaf/p/7965782.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved