原题
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.
解析
TinyURL编码/解码
我的解法
Medium难度的题。。也是只有思路没有实现。。
我一开始的思路是有问题的,还尝试找出一种算法可以让长链和短链一一对应,但这种算法不存在,除非短链不限长度,但这样就失去了意义
一般的短链都是域名+6位长度的随机码组成,试想所有大小写+数字一共62个,那最多也只有62^6个短链,所以根本不能满足无限多的长链
查了一些资料,网上的解法大致分三种:
算法一(超复杂。。觉得没必要)
将长链进行md5加盐编码,所得32位;
8个一组(共4组),按16进制与0x3fffffff(30个1)与,即取后30位,忽略其他位;
30位分成6段,每段5位的数字作为字符表62个字符(大小写+0-9)的索引取得共6个字符;
md5一共4个8位共取4个6位字符,随便取一个即可作为短链。
算法二(有缺陷,长度不受控制,且会出现一个长链对多个短链)
直接用递增返回id作为短链,短链可以有无限多个
算法三(leetcode上面的最优解,觉得不复杂也比较可行)
最优解
public class TinyURL {
//用于存储长链接-短链接映射
private static Map<String, String> longShort = new HashMap();
//用于存储短链接-长链接映射
private static Map<String, String> shortLong = new HashMap();
private static String HOST = "www.tinyUrl.com/";
// Encodes a URL to a shortened URL.
public static String encode(String longUrl) {
//如果映射中存在key则直接返回
if (longShort.containsKey(longUrl)) {
return HOST + longShort.get(longUrl);
}
//构造短链
String shortUrl;
String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
//碰撞直到没有重复
do {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 6; i++) {
int n = (int) (Math.random() * chars.length());
sb.append(chars.charAt(n));
}
shortUrl = sb.toString();
} while (shortLong.containsKey(shortUrl));
//存储并返回
shortLong.put(shortUrl, longUrl);
longShort.put(longUrl, shortUrl);
return HOST + shortUrl;
}
// Decodes a shortened URL to its original URL.
public static String decode(String shortUrl) {
return shortLong.get(shortUrl.replace(HOST, ""));
}
}