算法7 编码和解码TinyURL
2017-10-09 10:59
204 查看
题目:
TinyURL是一个URL缩短服务,您可以在其中输入URL,https://leetcode.com/problems/design-tinyurl并返回一个简短的URL http://tinyurl.com/4e9iAk。
设计TinyURL服务的方法encode和decode方法。编码/解码算法应该如何工作没有限制。您只需确保将URL编码为一个小型URL,并将该小型URL解码为原始URL。
思路:就是将有长的url有规律的变成短的url,就形成键值的模式。
代码:
此外还有一种相近的方式
还有一种随机数的方式
TinyURL是一个URL缩短服务,您可以在其中输入URL,https://leetcode.com/problems/design-tinyurl并返回一个简短的URL http://tinyurl.com/4e9iAk。
设计TinyURL服务的方法encode和decode方法。编码/解码算法应该如何工作没有限制。您只需确保将URL编码为一个小型URL,并将该小型URL解码为原始URL。
思路:就是将有长的url有规律的变成短的url,就形成键值的模式。
代码:
public class Codec { Map<Integer, String> map = new HashMap<>(); int i=0; public String encode(String longUrl) { map.put(i,longUrl); return "http://tinyurl.com/"+i++; } public String decode(String shortUrl) { return map.get(Integer.parseInt(shortUrl.replace("http://tinyurl.com/", ""))); } }
此外还有一种相近的方式
public class Codec { Map<Integer, String> map = new HashMap<>(); public String encode(String longUrl) { map.put(longUrl.hashCode(),longUrl); return "http://tinyurl.com/"+longUrl.hashCode(); } public String decode(String shortUrl) { return map.get(Integer.parseInt(shortUrl.replace("http://tinyurl.com/", ""))); } }
还有一种随机数的方式
public class Codec { Map<Integer, String> map = new HashMap<>(); Random r=new Random(); int key=r.nextInt(10000); public String encode(String longUrl) { while(map.containsKey(key)) key= r.nextInt(10000); map.put(key,longUrl); return "http://tinyurl.com/"+key; } public String decode(String shortUrl) { return map.get(Integer.parseInt(shortUrl.replace("http://tinyurl.com/", ""))); } }
相关文章推荐
- Base64 算法原理,以及编码、解码【加密、解密】 介绍
- Base64 算法原理,以及编码、解码【加密、解密】 介绍
- chunked 编码 解码 c算法 - yaneng的专栏 - 博客频道 - CSDN.NET
- Base64 编码解码算法(JS版)
- VB里Base64编码与解码算法
- VB里另一种更高效的Base64编码与解码算法
- 算法:计数,编码,解码
- C++ base64编码和解码算法
- QR二维码编码解码原理算法介绍
- 基于JavaScript的Base64编码、解码算法 推荐
- Base64 算法原理,以及编码、解码【加密、解密】 介绍
- GeoHash 经纬度坐标编码与解码算法
- Huffam 编码、解码和生成编码表算法实现
- Base64 编码解码算法(JS版)[备忘录]
- Base64 算法原理,以及编码、解码【加密、解密】 介绍
- Base64 算法原理,以及编码、解码【加密、解密】 介绍
- javascript utf-8 url 编码 之 纯算法 解码 by shawl.qiu 2007-9-24
- URL编码 百分号编码和解码 URLEncoder和URLDecoder的大致实现原理
- java.net.URLEncoder和java.net.URLDecoder的使用和js 中编码(encode)和解码(decode)方法
- iOS开发中Objective-C 对 URL的URLEncode(编码)与URLDecode(解码)