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.
编码的方式可以有很多种,因为一般都会受到Integer范围的限制,所以说可以选择固定长度的编码形式
public class Codec {
String alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random r = new Random();
Map<String, String> map = new HashMap<>();
String key = getString();
private String getString(){
StringBuffer sb = new StringBuffer();
for(int i = 0; i < 6; i++){
sb.append(alphabet.charAt(r.nextInt(62)));
}
return sb.toString();
}
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
while(map.containsKey(key)){
key = getString();
}
map.put(key, longUrl);
return "http://tinyurl.com/" + key;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return map.get(shortUrl.replace("http://tinyurl.com/", ""));
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));