-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path04.DesignURLShortenerBit.ly.java
More file actions
73 lines (63 loc) · 2.58 KB
/
04.DesignURLShortenerBit.ly.java
File metadata and controls
73 lines (63 loc) · 2.58 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
/* ---------------------------------------------------------------------------- */
/* ( The Authentic JS/JAVA CodeBuff )
___ _ _ _
| _ ) |_ __ _ _ _ __ _ __| |_ __ ____ _ (_)
| _ \ ' \/ _` | '_/ _` / _` \ V V / _` || |
|___/_||_\__,_|_| \__,_\__,_|\_/\_/\__,_|/ |
|__/
*/
/* -------------------------------------------------------------------------- */
/* Youtube: https://youtube.com/@code-with-Bharadwaj */
/* Github : https://github.com/Manu577228 */
/* Portfolio : https://manu-bharadwaj-portfolio.vercel.app/portfolio */
/* ----------------------------------------------------------------------- */
import java.util.HashMap;
public class URLShortener {
private HashMap<String, String> urlDb;
private HashMap<String, String> reverseDb;
private long counter;
private final String alphabet;
public URLShortener() {
urlDb = new HashMap<>();
reverseDb = new HashMap<>();
counter = 1;
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
}
private String encode(long num) {
if (num == 0) return "" + alphabet.charAt(0);
StringBuilder sb = new StringBuilder();
int base = alphabet.length();
while (num > 0) {
sb.append(alphabet.charAt((int)(num % base)));
num /= base;
}
return sb.reverse().toString();
}
public String shorten(String longUrl) {
if (reverseDb.containsKey(longUrl)) {
return reverseDb.get(longUrl);
}
String shortUrl = encode(counter);
urlDb.put(shortUrl, longUrl);
reverseDb.put(longUrl, shortUrl);
counter++;
return shortUrl;
}
public String retrieve(String shortUrl) {
return urlDb.getOrDefault(shortUrl, null);
}
// -------------------------------
// Demo
// -------------------------------
public static void main(String[] args) {
URLShortener shortener = new URLShortener();
String url1 = "https://www.youtube.com/@code-with-Bharadwaj";
String url2 = "https://github.com/Manu577228";
String s1 = shortener.shorten(url1);
String s2 = shortener.shorten(url2);
System.out.println("Short URL for YouTube: " + s1);
System.out.println("Short URL for GitHub : " + s2);
System.out.println("Retrieve YouTube URL : " + shortener.retrieve(s1));
System.out.println("Retrieve GitHub URL : " + shortener.retrieve(s2));
}
}