首页 技术 正文
技术 2022年11月18日
0 收藏 726 点赞 2,317 浏览 1712 个字

Question

535. Encode and Decode TinyURL

Solution

题目大意:实现长链接加密成短链接,短链接解密成长链接

思路:加密成短链接+key,将长链接按key保存到map,解密时根据短链接提取key,再从map中返回长链接

Java实现:

public class Codec {    // https://leetcode.com/problems/design-tinyurl --> http://tinyurl.com/4e9iAk
Map<Integer, String> map = new HashMap<>();
int i = 0; // Encodes a URL to a shortened URL.
public String encode(String longUrl) {
map.put(i, longUrl);
return "http://tinyurl.com/" + (i++);
} // Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
int key = Integer.parseInt(shortUrl.substring(shortUrl.lastIndexOf("/") + 1));
return map.get(key);
}
}// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));

Ref

https://leetcode.com/problems/encode-and-decode-tinyurl/discuss/100270/Three-different-approaches-in-java

Using simple counter

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/", "")));
}
}

Using hashcode

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/", "")));
}
}

Using random function

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/", "")));
}
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,965
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,486
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,331
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,114
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,747
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,781