Created
December 31, 2020 02:54
-
-
Save wkdalsgh192/3b148c2afc517a7d78f136ecc3e200d9 to your computer and use it in GitHub Desktop.
535. Encode and Decode TinyURL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.Map; | |
public class Codec { | |
// Encodes a URL to a shortened URL. | |
private final static String prefix = "http://tinyurl.com/"; | |
public static Map<String, String> map = new HashMap<>(); | |
public String encode(String longUrl) { | |
Integer hashcode = longUrl.hashCode(); | |
System.out.println(hashcode); | |
String hexStr = Integer.toHexString(hashcode); | |
System.out.println(hexStr); | |
String shortUrl = prefix+hexStr; | |
map.put(shortUrl, longUrl); | |
return shortUrl; | |
} | |
// Decodes a shortened URL to its original URL. | |
public String decode(String shortUrl) { | |
return map.get(shortUrl); | |
} | |
public static void main(String[] args) { | |
new Codec().encode("https://leetcode.com/problems/design-tinyurl"); | |
new Codec().decode("https://tinyurl.com/design-tinyurl"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment