public class Codec {
private HashMap<String, String> code2url = new HashMap<String, String>();
//private HashMap<String, String> url2code = new HashMap<String, String>();
private String candidates = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
private Random rand = new Random();
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
String code = "";
do {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 6; i++) {
sb.append(candidates.charAt(rand.nextInt(62)));
}
code = sb.toString();
}while(code2url.containsKey(code));
code2url.put(code, longUrl);
//url2code.put(longUrl,code);
return code;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return code2url.get(shortUrl);
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));