This is the solution about Leetcode-Encode and Decode TinyURL.

Description

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.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.concurrent.ThreadLocalRandom;
public class Codec {
HashMap<String, String> dicIndexURL = new HashMap<>();
HashMap<String, String> dicURLIndex = new HashMap<>();
static String BASE_HOST = "http://tinyurl.com/";
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
String charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
String key = null;
do{
StringBuilder sb = new StringBuilder();
for(int i=0; i<6; i++) {
int randomNum = ThreadLocalRandom.current().nextInt(0, charSet.length());
sb.append(charSet.charAt(randomNum));
}
key = sb.toString();
}while(dicIndexURL.containsKey(key));
dicIndexURL.put(key,longUrl);
dicURLIndex.put(longUrl,key);
return BASE_HOST+key;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return dicIndexURL.get(shortUrl.replace(BASE_HOST,""));
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));