535.Encode and Decode TinyURL

Solution 1: accepted 7ms

Increment and simply mapping the index.

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
public class Codec {
private static HashMap<String, String> stl = new HashMap<>();
private static HashMap<String, String> lts = new HashMap<>();
private final String BASE_URL = "http://tinyurl.com/";
private static char[] dic = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
int size = stl.size();
String tiny = getTiny(size);
stl.put(tiny, longUrl);
lts.put(longUrl, tiny);
return BASE_URL + tiny;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
String tiny = shortUrl.substring(shortUrl.length() - 6, shortUrl.length());
return stl.get(tiny);
}
public String getTiny(int size) {
String tiny = "";
for (int i = 0; i < 6; i++) {
tiny += dic[size%62];
size /= 62;
}
return tiny;
}
}

Solution 2: accepted 5ms

This solution will use more space but has better performance.

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
public class Codec {
private static HashMap<String, String> stl = new HashMap<>();
private static HashMap<String, String> lts = new HashMap<>();
private final String BASE_URL = "http://tinyurl.com/";
private static char[] dic = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
int size = stl.size();
String tiny = BASE_URL + getTiny(size); // store the leading url as well
stl.put(tiny, longUrl);
lts.put(longUrl, tiny);
return tiny;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return stl.get(shortUrl);
}
public String getTiny(int size) {
String tiny = "";
for (int i = 0; i < 6; i++) {
tiny += dic[size%62];
size /= 62;
}
return tiny;
}
}

Notes

Integer.toString(i, radix), 2 <= radix <= 36. For example, Integer.toString(11112222, 0) will give 6m68u.