Encode and Decode TinyURL

535. Encode and Decode TinyURL

TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk.

Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.

public class Codec {  
    private int globalID = 0;
    private Map<Integer, String> idToURL = new HashMap<>();
    private Map<String, Integer> urlToID = new HashMap<>();

    private String getShortKey(String url) {
        return url.substring("http://tinyurl.com/".length());
    }

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

        return c - 'A' + 36;
    }

    private int shortKeyToID(String shortKey) {
        int id = 0;

        for (int i = 0; i < shortKey.length(); i++) {
            id = id * 62 + toBase62(shortKey.charAt(i));
        }

        return id;
    }

    private String idToShortKey(int id) {
        String chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String shortURL = "";

        while (id > 0) {
            shortURL = chars.charAt(id % 62) + shortURL;
            id = id / 62;
        }

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

        return shortURL;
    }

    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        if (urlToID.containsKey(longUrl)) {
            return "http://tinyurl.com/" + idToShortKey(urlToID.get(longUrl));
        }

        globalID++;
        urlToID.put(longUrl, globalID);
        idToURL.put(globalID, longUrl);

        return "http://tinyurl.com/" + idToShortKey(globalID);
    }

    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
        String shortKey = getShortKey(shortUrl);
        int id = shortKeyToID(shortKey);

        return idToURL.get(id);
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));

Hope this helps,
Michael