算法7 编码和解码TinyURL

来源:互联网 发布:卷积神经网络 算法 编辑:程序博客网 时间:2024/06/05 20:59

题目:
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/", "")));    }}
原创粉丝点击