535. Encode and Decode TinyURL
Last updated
Last updated
/**
* 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));