您的位置:首页 > 其它

535. Encode and Decode TinyURL

2017-03-16 19:51 549 查看
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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  codec