The short_url you return should be unique short url and start withhttp://tiny.url/and6acceptable characters. For example "http://tiny.url/abcD9E" or something else.
The long_url should behttp://www.lintcode.com/faq/?id=10in this case.
Note
两种方法,随机或者base62
都要建立long和short的映射关系
Code
// version 1: RandompublicclassTinyUrl {privateMap<String,String> long2Short;privateMap<String,String> short2Long;publicTinyUrl() { long2Short =newHashMap<String,String>(); short2Long =newHashMap<String,String>(); } /** * @param url a long url * @return a short url starts with http://tiny.url/ */publicStringlongToShort(String url) {if (long2Short.containsKey(url)) {returnlong2Short.get(url); }while (true) {String shortURL =generateShortURL();if (!short2Long.containsKey(shortURL)) {short2Long.put(shortURL, url);long2Short.put(url, shortURL);return shortURL; } } } /** * @param url a short url starts with http://tiny.url/ * @return a long url */publicStringshortToLong(String url) {if (!short2Long.containsKey(url)) {returnnull; }returnshort2Long.get(url); }privateStringgenerateShortURL() {String allowedChars ="0123456789"+"abcdefghijklmnopqrstuvwxyz"+"ABCDEFGHIJKLMNOPQRSTUVWXYZ";Random rand =newRandom();String shortURL ="http://tiny.url/";for (int i =0; i <6; i++) {int index =rand.nextInt(62); shortURL +=allowedChars.charAt(index); }return shortURL; }}
/ version 2: base62publicclassTinyUrl {publicstaticint GLOBAL_ID =0;privateHashMap<Integer,String> id2url =newHashMap<Integer,String>();privateHashMap<String,Integer> url2id =newHashMap<String,Integer>();privateStringgetShortKey(String url) {returnurl.substring("http://tiny.url/".length()); }privateinttoBase62(char c) {if (c >='0'&& c <='9') {return c -'0'; }if (c >='a'&& c <='z') {return c -'a'+10; }return c -'A'+36; }privateintshortKeytoID(String short_key) {int id =0;for (int i =0; i <short_key.length(); ++i) { id = id *62+toBase62(short_key.charAt(i)); }return id; }privateStringidToShortKey(int id) {String chars ="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";String short_url ="";while (id >0) { short_url =chars.charAt(id %62) + short_url; id = id /62; }while (short_url.length() <6) { short_url ="0"+ short_url; }return short_url; } /** * @param url a long url * @return a short url starts with http://tiny.url/ */publicStringlongToShort(String url) {if (url2id.containsKey(url)) {return"http://tiny.url/"+idToShortKey(url2id.get(url)); } GLOBAL_ID++;url2id.put(url, GLOBAL_ID);id2url.put(GLOBAL_ID, url);return"http://tiny.url/"+idToShortKey(GLOBAL_ID); } /** * @param url a short url starts with http://tiny.url/ * @return a long url */publicStringshortToLong(String url) {String short_key =getShortKey(url);int id =shortKeytoID(short_key);returnid2url.get(id); }}