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


Log in to reply
 

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