TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl
and it returns a short URL such as http://tinyurl.com/4e9iAk
.
Design the encode
and decode
methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
说白了就是要你把长网址变成短网址,再将短网址转化成对应的长网址,而且方法不限,所以可以随意发挥,容易AC
这里长网址变成短网址采用的方法是,定义一个常量字符串0-9a-zA-Z,每次将长网址作为key存入Map时,在将对应的短网址(在那个字符串常量中随机挑去6个作为短网址)作为对应的value存入map中,在将两者对换,存入另一个map中,用于将短网址变成长网址。存入过程中会判断长网址是否出现过,以及随机生成的短网址是否出现过,在做相应处理。
代码如下
public class Codec {
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=null;
if(longUrlToShortUrl.get(longUrl)!=null)
{
return longUrlToShortUrl.get(longUrl);
}
else
{
encode = Codec.encodeUrl();
while(shortUrlToLongUrl.get(encode)!=null)
{
encode = Codec.encodeUrl();
}
longUrlToShortUrl.put(longUrl,encode);
shortUrlToLongUrl.put(encode, longUrl);
return encode;
}
}
public static String encodeUrl(){
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 decode = shortUrlToLongUrl.get(shortUrl);
return decode == null ? "" : decode;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));