public class Codec {
// Encodes a URL to a shortened URL.
private String prefix = "http://tinyurl.com/";
private static Map<String,String> indexMap = new HashMap<String,String>();
private static Map<String,String> reverseMap = new HashMap<String,String>();
private static final String code = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
if(indexMap.containsKey(longUrl)){
return indexMap.get(longUrl);
}
StringBuffer shortUrl = new StringBuffer();
do{
for(int i=0;i<6;i++){
int n = (int)Math.random()*code.length();
shortUrl.append(code.charAt(n));
}
}while(reverseMap.containsKey(shortUrl));
String res = prefix+shortUrl.toString();
reverseMap.put(res, longUrl);
indexMap.put(longUrl, res);
return res;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return reverseMap.get(shortUrl);
}
}
535. Encode and Decode TinyURL
最新推荐文章于 2019-10-28 16:49:29 发布