Note: This is a companion problem to the

System Design problem: Design TinyURL.

TinyURL is a URL shortening service where you enter a URL such ashttps://leetcode.com/problems/design-tinyurland it returns a short URL such ashttp://tinyurl.com/4e9iAk.

Design theencodeanddecodemethods 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 String s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    private HashMap<String, Integer> map1 = new HashMap<>();
    private HashMap<Integer, String> map2 = new HashMap<>();

    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        if(!map1.containsKey(longUrl)) {
            map1.put(longUrl, map1.size() + 1);
            map2.put(map1.size(), longUrl);
        }

        int id = map1.get(longUrl);
        StringBuilder res = new StringBuilder();
        int len = s.length();

        while(id > 0) {
            int index = id % len;
            res.append(s.charAt(index));
            id /= 62;
        }

        return res.toString();
    }

    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
        int id = 0;
        int len = s.length();

        for(int i = shortUrl.length() - 1; i >= 0; i--) {
            id = id * len + s.indexOf(shortUrl.charAt(i));
        }

        return map2.get(id);
    }
}

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

results matching ""

    No results matching ""