- Use sequenced ID
public class Codec {
String chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String prefix = "https://www.amz/";
HashMap<String, String> map = new HashMap<>();
int count = 1;
private String genShortUrl() {
int c = count;
StringBuilder sb = new StringBuilder();
while (c > 0) {
char ch = chars.charAt(c % 62);
sb.append(ch);
c /= 62;
}
return sb.toString();
}
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
String shortUrl = genShortUrl();
map.put(shortUrl, longUrl);
count++;
return prefix + shortUrl;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
shortUrl = shortUrl.replace(prefix, "");
if (map.containsKey(shortUrl)) {
return map.get(shortUrl);
} else {
return "";
}
}
}
- Use 6 bits random generate key
public class Codec {
String alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
HashMap<String, String> map = new HashMap<>();
Random rand = new Random();
String key = getRand();
public String getRand() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 6; i++) {
sb.append(alphabet.charAt(rand.nextInt(62)));
}
return sb.toString();
}
public String encode(String longUrl) {
while (map.containsKey(key)) {
key = getRand();
}
map.put(key, longUrl);
return "http://tinyurl.com/" + key;
}
public String decode(String shortUrl) {
return map.get(shortUrl.replace("http://tinyurl.com/", ""));
}
}