Skip to content

Commit a72b658

Browse files
authored
Create 0535. Encode and Decode TinyURL
1 parent 5354a33 commit a72b658

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

0535. Encode and Decode TinyURL

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/****************************************
2+
535. Encode and Decode TinyURL
3+
4+
Difficulty: Medium
5+
6+
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl
7+
and it returns a short URL such as http://tinyurl.com/4e9iAk.
8+
9+
Design the encode and decode methods for the TinyURL service.
10+
There is no restriction on how your encode/decode algorithm should work.
11+
You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
12+
13+
****************************************/
14+
15+
16+
public class Codec {
17+
18+
private Map<Integer, String> map = new HashMap();
19+
20+
// Encodes a URL to a shortened URL.
21+
public String encode(String longUrl) {
22+
int encode = longUrl.hashCode();
23+
map.put(encode, longUrl);
24+
return "http://tinyurl.com/" + encode;
25+
}
26+
27+
// Decodes a shortened URL to its original URL.
28+
public String decode(String shortUrl) {
29+
int decode = Integer.parseInt(shortUrl.replace("http://tinyurl.com/", ""));
30+
return map.get(decode);
31+
32+
}
33+
}
34+
35+
// Your Codec object will be instantiated and called as such:
36+
// Codec codec = new Codec();
37+
// codec.decode(codec.encode(url));

0 commit comments

Comments
 (0)