publicclassCodec{// shortUrl -> longMap<String,String> codeDb =newHashMap<>();// longUrl -> shortMap<String,String> urlDb =newHashMap<>();staticfinalString chars ="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";// Generate codeprivateStringgenerateCode(){char[] code =newchar[6];for(int i =0; i <6;++i){
code[i]= chars.charAt((int)(Math.random()*62));}return"http://tinyurl.com/"+String.valueOf(code);}// Encodes a URL to a shortened URL.publicStringencode(String longUrl){// Check if already in dbif(urlDb.containsKey(longUrl))return urlDb.get(longUrl);String code =generateCode();// In case duplicate code appearswhile(codeDb.containsKey(code)) code =generateCode();// Store to db
codeDb.put(code, longUrl);
urlDb.put(longUrl, code);return code;}// Decodes a shortened URL to its original URL.publicStringdecode(String shortUrl){return codeDb.get(shortUrl);}}// Your Codec object will be instantiated and called as such:// Codec codec = new Codec();// codec.decode(codec.encode(url));