Question

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 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.

Solution

  • Method 1: HashMap + hashCode
    public class Codec {
        private Map<Integer, String> map = new HashMap<>();
        private int index;
        // Encodes a URL to a shortened URL.
        public String encode(String longUrl) {
            int key = longUrl.hashCode();
            this.map.put(key, longUrl);
            return "http://tinyurl.com/" + longUrl.hashCode();
        }
    
        // Decodes a shortened URL to its original URL.
        public String decode(String shortUrl) {
            return map.get(Integer.parseInt(shortUrl.replace("http://tinyurl.com/", "")));
        }
    }
    
    // Your Codec object will be instantiated and called as such:
    // Codec codec = new Codec();
    // codec.decode(codec.encode(url));
    
  • Method 2: HashMap + count
    public class Codec {
        private Map<Integer, String> map = new HashMap<>();
        private int index;
        // Encodes a URL to a shortened URL.
        public String encode(String longUrl) {
            this.map.put(index, longUrl);
            return "http://tinyurl.com/" + index++;
        }
    
        // Decodes a shortened URL to its original URL.
        public String decode(String shortUrl) {
            return map.get(Integer.parseInt(shortUrl.replace("http://tinyurl.com/", "")));
        }
    }
    
    // Your Codec object will be instantiated and called as such:
    // Codec codec = new Codec();
    // codec.decode(codec.encode(url));
    

Amazon session

public class Codec {
    private static final String prefix = "http://tinyurl.com/";
    private Map<String, String> map = new HashMap<>();
    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        String hash = "" + longUrl.hashCode();
        map.put(hash, longUrl);
        return prefix + hash;
    }

    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
        int index = shortUrl.lastIndexOf("/");
        String hash = shortUrl.substring(index + 1);
        return map.get(hash);
    }
}

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