Last active
June 16, 2017 06:13
-
-
Save xynophon/88d71a5171e204aff501ea2becb030b7 to your computer and use it in GitHub Desktop.
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.math.BigInteger; | |
| import java.util.HashMap; | |
| public class Codec { | |
| String header = "http://tinyurl.com/"; | |
| static BigInteger num = new BigInteger("0"); | |
| String t = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; | |
| HashMap<String, String> decoding = new HashMap<>(); | |
| HashMap<String, String> encoding = new HashMap<>(); | |
| public String num_to_62system(BigInteger num) { | |
| BigInteger temp[] = num.divideAndRemainder(BigInteger.valueOf(62)); | |
| if (temp[0].intValue() == 0) { | |
| return Character.toString(t.charAt(temp[1].intValue())); | |
| } else { | |
| return num_to_62system(temp[0]) + Character.toString(t.charAt(temp[1].intValue())); | |
| } | |
| } | |
| // Encodes a URL to a shortened URL. | |
| public String encode(String longUrl) { | |
| if (encoding.containsKey(longUrl)) { | |
| return encoding.get(longUrl); | |
| }else { | |
| String key = String.format("%6s", num_to_62system(num)).replace(' ', '0'); | |
| encoding.put(longUrl, key); | |
| decoding.put(key, longUrl); | |
| num = num.add(BigInteger.valueOf(1)); | |
| return header + key; | |
| } | |
| } | |
| // Decodes a shortened URL to its original URL. | |
| public String decode(String shortUrl) { | |
| String key = shortUrl.split(header)[1]; | |
| return decoding.get(key); | |
| } | |
| public static void main(String[] args) { | |
| Codec c = new Codec(); | |
| String shortUrl = c.encode("https://leetcode.com/problems/design-tinyurl"); | |
| System.out.println(c.decode(shortUrl)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment