TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl
and it returns a short URL such as http://tinyurl.com/4e9iAk
.
Design the encode
and decode
methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
题意:
设计一个短网址的编解码器
code
1 public class Codec { 2 3 private static final String SEED = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; 4 private static final String BASE = "http://tinyurl.com/"; 5 6 private static Map<String, String> keyToURL = new HashMap<>(); 7 private static Map<String, String> urlToKey = new HashMap<>(); 8 9 public static void main(String[] args) { 10 String tinyURL = encode("http://thisislongurl.com/abcd/123"); 11 String longURL = decode(tinyURL); 12 13 System.out.println("tinyURL = " + tinyURL); 14 System.out.println("longURL = " + longURL); 15 } 16 17 public static String encode(String longUrl) { 18 if (longUrl == null || longUrl.isEmpty()) { 19 return null; 20 } 21 if (urlToKey.containsKey(longUrl)) { 22 return BASE + urlToKey.get(longUrl); 23 } 24 25 StringBuilder key = null; 26 27 // keep generating keys until a unique one is found 28 do { 29 key = new StringBuilder(); 30 for (int i = 0; i < 6; i++) { 31 int r = (int)(Math.random() * SEED.length()); 32 key.append(SEED.charAt(r)); 33 } 34 } while (keyToURL.containsKey(key)); 35 36 keyToURL.put(key.toString(), longUrl); 37 urlToKey.put(longUrl, key.toString()); 38 39 return BASE + key; 40 } 41 42 public static String decode(String shortUrl) { 43 if (shortUrl == null || shortUrl.isEmpty()) { 44 return ""; 45 } 46 String[] shortUrlSplits = shortUrl.split("/"); 47 return keyToURL.get(shortUrlSplits[shortUrlSplits.length - 1]); 48 } 49 }