public class Codec {
//还是利用HashMap,将longUrl和shortUrl对应起来
//建立两个hashMap
Map<String,String> LongUrlToShortUrl=new HashMap<>();
Map<String,String> ShortUrlToLongUrl=new HashMap<>();
private static final String code = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
String encode="";
if(LongUrlToShortUrl.get(longUrl)!=null){
return LongUrlToShortUrl.get(longUrl);
//如果map中存在则直接返回
}else{
encode=Codec.randoms(longUrl);
while(ShortUrlToLongUrl.get(encode)!=null){
encode=Codec.randoms(longUrl);
}
}
LongUrlToShortUrl.put(longUrl,encode);
ShortUrlToLongUrl.put(encode,longUrl);
return encode;
}
public static String randoms(String longUrl){
String encode="";
for(int i=0; i<6; i++)
{
String str = String.valueOf(code.charAt((int)(Math.random()*61)));
encode = encode + str;
}
return encode;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
String decodes=ShortUrlToLongUrl.get(shortUrl);
if(decodes==null) return "";
else return decodes;
}
}
leetcode 535. Encode and Decode TinyURL
最新推荐文章于 2026-06-28 11:41:56 发布
本文介绍了一种基于HashMap的URL缩略算法实现方法。通过使用两个HashMap分别存储长链接到短链接及短链接到长链接的映射关系,确保了链接的唯一性和可逆性。此外,还提供了一个生成随机字符串的方法用于创建短链接。

480

被折叠的 条评论
为什么被折叠?



