Java using UUID


  • 0
    G
    import java.util.UUID;
    public class Codec {
        static HashMap<String, String> encodes = new HashMap<>();
        // Encodes a URL to a shortened URL.
        public String encode(String longUrl) {
            String slug = UUID.randomUUID().toString().substring(0,5);
            encodes.put(slug, longUrl);
            return ("http://tinyurl.com/" + slug);
        }
    
        // Decodes a shortened URL to its original URL.
        public String decode(String shortUrl) {
            if(shortUrl == null || shortUrl.isEmpty())
                return "";
            String key = shortUrl.substring(shortUrl.length() - 5);
            return encodes.get(key);
            
        }
    }
    

Log in to reply
 

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