Skip to content

Instantly share code, notes, and snippets.

@WaltXin
Last active June 12, 2021 05:42
Show Gist options
  • Save WaltXin/ba5f8758447930d44f4b89e317cfa007 to your computer and use it in GitHub Desktop.
Save WaltXin/ba5f8758447930d44f4b89e317cfa007 to your computer and use it in GitHub Desktop.
TinyURL design
  1. 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 "";
        }
    }
}
  1. 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/", ""));
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment