Encode and Decode TinyURL (M)
题目
Note: This is a companion problem to the System Design problem: Design TinyURL.
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.
题意
设计一个能将长URL和短URL互相转换的功能。
思路
无特定方法。
代码实现
Java
public class Codec {
private Map<String, String> toLong = new HashMap<>();
private Map<String, String> toShort = new HashMap<>();
private String pool = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private Random random = new Random();
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
String suffix = randomSuffix(5);
if (toShort.containsKey(longUrl)) {
suffix = toShort.get(longUrl);
} else {
while (suffix == null || toLong.containsKey(suffix)) {
suffix = randomSuffix(5);
}
toLong.put(suffix, longUrl);
toShort.put(longUrl, suffix);
}
return "http://tinyurl.com/" + suffix;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return toLong.get(shortUrl.split("/", 4)[3]);
}
private String randomSuffix(int len) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
sb.append(pool.charAt(random.nextInt(62)));
}
return sb.toString();
}
}