[leetcode] problem 535 – encode and decode 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.

Code

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
private final String ALPHA_NUMERIC_STRING = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

private Map<String, String> shortToLong = new HashMap<>();
private Map<String, String> longToShort = new HashMap<>();
private String URL = "http://tinyurl.com/";
private int SIZE = 6;

public String (String longUrl) {
if (longToShort.containsKey(longUrl))
return URL + longToShort.get(longUrl);

int hash = 0;
StringBuilder shortUrl = new StringBuilder();
int length = ALPHA_NUMERIC_STRING.length();

for (int i = 0; i < SIZE; i++)
hash += (int) Math.random();

while (hash != 0 && shortUrl.length() < SIZE) {
shortUrl.append(ALPHA_NUMERIC_STRING.charAt(hash % length));
hash /= length;
}

longToShort.put(longUrl, shortUrl.toString());
shortToLong.put(shortUrl.toString(), longUrl);
return URL + shortUrl.toString();
}

public String decode(String shortUrl) {
String hash = shortUrl.substring(shortUrl.lastIndexOf("/") + 1);
return shortToLong.get(hash);
}