535. Encode and Decode TinyURL
Description
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.
Constraints
Approach
Links
GeeksforGeeks
ProgramCreek
YouTube
Examples
Solutions
/**
* Time complexity :
* Space complexity :
*/
public class Codec {
private Map<String, String> longShortMap = new HashMap();
private Map<String, String> shortLongMap = new HashMap();
private final String TINY_URL = "http://tinyurl.com/";
private int id = 0;
private String code = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
if(longShortMap.containsKey(longUrl)) {
return longShortMap.get(longUrl);
}
StringBuilder shortUrl = new StringBuilder();
int currId = id;
for(int i = 0; i < 6; i++) {
int codeIndex = currId % 62;
currId /= 62;
shortUrl.append(code.charAt(codeIndex));
}
longShortMap.put(longUrl, shortUrl.toString());
shortLongMap.put(shortUrl.toString(), longUrl);
id++;
return TINY_URL + shortUrl.toString();
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return shortLongMap.get(shortUrl.replace(TINY_URL, ""));
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));
Follow up
Last updated
Was this helpful?