/*
思路:建立两个map 一个是内容对应结果字符串, 一个是结果字符串对应内容;
还需要一个包含所有大小写字母和数字的字符串 储存变换过来的url
1. 先随机生成一个6位的字符串,(可以储存62^6个url),如果重复则重新生成,变量名叫key;把两个map都存好;
2. decode 时 直接找map2里面的key就能得到原来的url;
*/
public class Codec {
private Map<String, String> map1 = new HashMap<>();
private Map<String, String> map2 = new HashMap<>();
private String s = "http://tinyurl.com/";
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
String charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
if(map1.containsKey(longUrl)) return s + map1.get(longUrl);
String key;
do {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < 6; i++) {
int r = (int)(Math.random() * (charSet.length() - 1));
sb.append(charSet.charAt(r));
}
key = sb.toString();
} while(map2.containsKey(key));
map1.put(longUrl, key);
map2.put(key, longUrl);
return s + key;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
shortUrl = shortUrl.replace(s, "");
return map2.get(shortUrl);
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));