Skip to content

Instantly share code, notes, and snippets.

@wkdalsgh192
Created December 31, 2020 02:54
Show Gist options
  • Save wkdalsgh192/3b148c2afc517a7d78f136ecc3e200d9 to your computer and use it in GitHub Desktop.
Save wkdalsgh192/3b148c2afc517a7d78f136ecc3e200d9 to your computer and use it in GitHub Desktop.
535. Encode and Decode TinyURL
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