535. Encode and Decode TinyURL

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
33
34
35
36
37
38
39
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

public class Codec {

private static final String DICT = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static final int SHORT_LENGTH = 6;

private final Map<String, String> longToShortMap = new HashMap<>();
private final Map<String, String> shortToLongMap = new HashMap<>();


// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
String shortUrl = null;
while (!longToShortMap.containsKey(longUrl)) {
char[] chars = new char[SHORT_LENGTH];
for (int i = 0; i < chars.length; i++) {
chars[i] = DICT.charAt(ThreadLocalRandom.current().nextInt(DICT.length()));
}
shortUrl = new String(chars);
if (shortToLongMap.containsKey(shortUrl)) {
continue;
}
longToShortMap.put(longUrl, shortUrl);
shortToLongMap.put(shortUrl, longUrl);
}

return shortUrl;
}

// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return shortToLongMap.get(shortUrl);
}

}

References

535. Encode and Decode TinyURL