LeetCode 535. Encode and Decode TinyURL
原题链接在这里:https://leetcode.com/problems/encode-and-decode-tinyurl/
题目:
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.
题解:
数字count其实就是base不同的short url.
Time Complexity: encode, O(count). count每次除以62. decode, O(n). n是short url的长度.
Space: O(m). 连个映射的大小.
AC Java:
1 public class Codec { 2 HashMap<String, Integer> lToS = new HashMap<>(); 3 HashMap<Integer, String> sToL = new HashMap<>(); 4 int count = 1; 5 String elements = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 6 String head = "http://tinyurl.com/"; 7 8 // Encodes a URL to a shortened URL. 9 public String encode(String longUrl) { 10 if(lToS.containsKey(longUrl)){ 11 return head + convertToBase62(lToS.get(longUrl)); 12 } 13 14 String shortURL = convertToBase62(count); 15 lToS.put(longUrl, count); 16 sToL.put(count, longUrl); 17 count++; 18 return head + shortURL; 19 } 20 21 // Decodes a shortened URL to its original URL. 22 public String decode(String shortUrl) { 23 int n = convertToBase10(shortUrl.substring(head.length())); 24 return sToL.get(n); 25 } 26 27 private String convertToBase62(int n){ 28 StringBuilder sb = new StringBuilder(); 29 while(n > 0){ 30 sb.insert(0, elements.charAt(n % 62)); 31 n /= 62; 32 } 33 34 return sb.toString(); 35 } 36 37 private int convertToBase10(String s){ 38 int res = 0; 39 for(char c : s.toCharArray()){ 40 res = res * 62 + getInt(c); 41 } 42 43 return res; 44 } 45 46 private int getInt(char c){ 47 if(c >= '0' && c <= '9'){ 48 return c - '0'; 49 }else if(c >= 'a' && c <= 'z'){ 50 return c - 'a' + 10; 51 }else if(c >= 'A' && c <= 'Z'){ 52 return c - 'A' + 36; 53 } 54 55 return -1; 56 } 57 } 58 59 // Your Codec object will be instantiated and called as such: 60 // Codec codec = new Codec(); 61 // codec.decode(codec.encode(url));