Tiny Url

Implementation

public class TinyUrl {
    private static int GLOBAL_ID;
    private static String PREFIX = "http://tiny.url/";
    private static String CODE = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    Map<Integer, String> id2url = new HashMap<>();
    Map<String, Integer> url2id = new HashMap<>();

    public int toBase62(char c) {
        if (c >= '0' && c <= '9') {
            return c - '0';
        }
        else if (c >= 'a' && c <= 'z') {
            return c - 'a' + 10;
        }
        else {
            return c -'A' + 36;
        }
    }

    public String idToShortKey(int id) {
        String key = "";
        while (id > 0) {
            key = CODE.charAt(id % 62) + key;
            id /= 62;
        }

        while (key.length() < 6) {
            key = "0" + key;
        }
        return key;
    }

    public int shortKeyToId(String key) {
        int id = 0;
        for (int i = 0; i < key.length(); i++) {
            id = id * 62 + toBase62(key.charAt(i));
        }
        return id;
    }

    public String getShortKey(String url) {
        return url.substring(PREFIX.length());
    }

    /**
     * @param url a long url
     * @return a short url starts with http://tiny.url/
     */
    public String longToShort(String url) {
        if (url2id.containsKey(url)) {
            return PREFIX + idToShortKey(url2id.get(url));
        }
        ++GLOBAL_ID;
        url2id.put(url, GLOBAL_ID);
        id2url.put(GLOBAL_ID, url);
        return PREFIX + idToShortKey(GLOBAL_ID);
    }

    /**
     * @param url a short url starts with http://tiny.url/
     * @return a long url
     */
    public String shortToLong(String url) {
        String shortKey = getShortKey(url);
        int id = shortKeyToId(shortKey);
        return id2url.get(id);
    }
}

Last updated