Encode and Decode TinyURL
public class Codec {
private Map<String,String> short2long;
private Map<String,String> long2short;
private String dic;
public Codec(){
short2long = new HashMap<>();
long2short = new HashMap<>();
dic = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
short2long.clear();
long2short.clear();
}
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
if(long2short.containsKey(longUrl)){
return "http://tinyurl.com/"+long2short.get(longUrl);
}
int index = 0;
Random r = new Random();
String randomStr = "";
for(int i =0; i < 6;i++){
randomStr += dic.charAt(r.nextInt(62));
}
while(short2long.containsKey(randomStr)){
int rdNum = r.nextInt(62);
randomStr = randomStr.substring(0,index) + dic.charAt(rdNum) + randomStr.substring(index+1);
//random string length 6
index = (index + 1) % 5;
}
long2short.put(longUrl,randomStr);
short2long.put(randomStr,longUrl);
return "http://tinyurl.com/"+randomStr;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
String str = shortUrl.substring(shortUrl.lastIndexOf("/")+1);
return short2long.containsKey(str) ? short2long.get(str) : shortUrl;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));Last updated