Note: This is a companion problem to the System Design problem: Design TinyURL.
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl
and it returns a short URL such as http://tinyurl.com/4e9iAk
.
Design the encode
and decode
methods for
the TinyURL service. There is no restriction on how your encode/decode
algorithm should work. 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.
<SOLVE>
public class Codec {
Map<Integer, String> map = new HashMap<>();
int i = 0;
public String encode(String longUrl) {
//System.out.println(longUrl);
map.put(i, longUrl);
return "http://tinyurl.com/" + i++;
}
public String decode(String shortUrl) {
return map.get(Integer.parseInt(shortUrl.replace("http://tinyurl.com/", "")));
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));
Map<Integer, String> map = new HashMap<>();
int i = 0;
public String encode(String longUrl) {
//System.out.println(longUrl);
map.put(i, longUrl);
return "http://tinyurl.com/" + i++;
}
public String decode(String shortUrl) {
return map.get(Integer.parseInt(shortUrl.replace("http://tinyurl.com/", "")));
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));
'Amazon > Leetcode' 카테고리의 다른 글
235. Lowest Common Ancestor of a Binary Search Tree (0) | 2018.07.31 |
---|---|
206. Reverse Linked List (0) | 2018.07.29 |
5. Longest Palindromic Substring (0) | 2018.07.29 |
617. Merge Two Binary Trees (0) | 2018.07.27 |
167. Two Sum II - Input array is sorted (0) | 2018.07.26 |