Created
October 16, 2015 21:23
-
-
Save gcrfelix/ac2fd9f394d8e71e75c2 to your computer and use it in GitHub Desktop.
This file contains 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
// http://www.geeksforgeeks.org/how-to-design-a-tiny-url-or-url-shortener/ | |
// http://stackoverflow.com/questions/742013/how-to-code-a-url-shortener | |
// https://github.com/delight-im/ShortURL/blob/master/Java/ShortURL.java | |
How to design a system that takes big URLs like “http://www.geeksforgeeks.org/count-sum-of-digits-in-numbers-from-1-to-n/” and | |
converts them into a short 6 character URL. It is given that URLs are stored in database and every URL has an associated integer id. | |
public class ShortURL { | |
public static final String ALPHABET = "23456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ-_"; | |
public static final int BASE = ALPHABET.length(); | |
public static String encode(int num) { | |
StringBuilder str = new StringBuilder(); | |
while (num > 0) { | |
str.insert(0, ALPHABET.charAt(num % BASE)); | |
num = num / BASE; | |
} | |
return str.toString(); | |
} | |
public static int decode(String str) { | |
int num = 0; | |
for (int i = 0; i < str.length(); i++) { | |
num = num * BASE + ALPHABET.indexOf(str.charAt(i)); | |
} | |
return num; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment