-
Notifications
You must be signed in to change notification settings - Fork 2
/
EncodeAndDecodeTinyURL.java
61 lines (50 loc) · 1.45 KB
/
EncodeAndDecodeTinyURL.java
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.algorithm.playground.leetcode.problems.lc500.lc530.lc535;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* https://leetcode.com/problems/encode-and-decode-tinyurl/description/
*/
public class EncodeAndDecodeTinyURL {
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));
public class Codec {
private Map<String, String> hashToUrl = new HashMap<>();
private Random rnd = new Random();
private String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
String key = getKey();
String host = getHost(longUrl);
while (hashToUrl.containsKey(key)) {
key = getKey();
}
hashToUrl.put(key, longUrl);
return host + key;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
String host = getHost(shortUrl);
return hashToUrl.get(shortUrl.replace(host, ""));
}
private String getKey() {
StringBuilder builder = new StringBuilder(8);
for (int i = 0; i < 8; i++) {
builder.append(alphabet.charAt(rnd.nextInt(alphabet.length())));
}
return builder.toString();
}
private String getHost(String s) {
int count = 0;
int idx = 0;
while (count < 3) {
if (s.charAt(idx) == '/') {
count++;
}
idx++;
}
return s.substring(0, idx);
}
}
}