您的位置:首页 > 其它

算法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,就形成键值的模式。

代码:

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/", "")));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法