Java Solution using two HashMaps

  • 0

    There are a lot of interesting solutions in this forum. This was the first thing that came to mind when I began the problem. In hindsight, random numbers,etc are maybe unnecessary.

    public class Codec {
        HashMap<String, String> encode = new HashMap<>();
        HashMap<String, String> decode = new HashMap<>();
        // Encodes a URL to a shortened URL.
        public String encode(String longUrl) {
           if(longUrl == null || longUrl.isEmpty()) return longUrl;
           StringBuilder tinyurl = new StringBuilder(""); 
           Random rand = new Random();
           int pre  = rand.nextInt(100);
           int end = rand.nextInt(100);
           tinyurl.append("m").append(pre).append("c").append(end).append("h").append((pre * end) % 17);
           decode.put(tinyurl.toString(), longUrl);
           return tinyurl.toString();
        // Decodes a shortened URL to its original URL.
        public String decode(String shortUrl) {
            if(shortUrl == null || shortUrl.isEmpty()) return shortUrl;
            return this.decode.getOrDefault(shortUrl,null);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.