Encode and Decode TinyURL


  • 0

    Click here to see the full article post


  • 0

    Using a combination of System.nanoTime() and hashCode().
    It produces urls in this format https://tinyurl.com/596293762700519

    // Encodes a URL to a shortened URL.
    HashMap<String,String> tinyUrlMap = new HashMap<>();
    HashMap<String,String> longUrlMap = new HashMap<>();
    String tinyPrefix = "https://tinyurl.com/";

    public String encode(String longUrl) {
    if(longUrlMap.containsKey(longUrl)) return longUrlMap.get(longUrl);
    String tinyUrl = tinyPrefix+(longUrl.hashCode()+System.nanoTime());
    tinyUrlMap.put(tinyUrl,longUrl);
    longUrlMap.put(longUrl,tinyUrl);
    return tinyUrl;
    }

    public String decode(String shortUrl) {
    return tinyUrlMap.get(shortUrl);
    }


  • 0
    F
    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        return longUrl;
    }
    
    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
        return shortUrl;
    }
    

    is Accepted ;)


  • 0
    R

    Do we need to de-dupe the long url? Can one same long url have multiple tinyUrls?


  • 0
    G

    Great Step by Step Solution


  • 0
    W

    The number of URLs that can be encoded is quite large in this case, nearly of the order (10 + 26 *2)^6. Why this number?


  • 0
    M

    @workSmart 10 digits, 26 upper and 26 lower letters, length is 6.


Log in to reply
 

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