forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEncodeandDecodeTinyURL.java
39 lines (31 loc) · 969 Bytes
/
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
// SC : O(n), no of urls that you have encoded
// TC : O(1)
public class Codec {
Map<String, String> map = new HashMap<>();
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
String key = ""+map.size();
map.put(key, longUrl);
return key;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return map.get(shortUrl);
}
}
public class Codec {
Map<String, String> map = new HashMap<>();
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
String key = ""+longUrl.hashCode();
map.put(key, longUrl);
return key;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return map.get(shortUrl);
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));