LeetCode Design TinyURL
原題鏈接在這里:https://leetcode.com/problems/design-tinyurl/description/
題目:
How would you design a URL shortening service that is similar to?TinyURL?
Background:
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.
Requirements:
?
Note about Questions:
Below are just a small subset of questions to get you started. In real world, there could be many follow ups and questions possible and the discussion is open-ended (No one true or correct way to solve a problem). If you have more ideas or questions, please ask in Discuss and we may compile it here!
Questions:
題解:
是System Design題目. 參考了這篇帖子.
按照SNAKE的方法逐個分析.
AC Java:
1 public class URLService{ 2 HashMap<String, Integer> ltos; 3 HashMap<Integer, String> stol; 4 static int COUNTER; 5 String elements; 6 7 URLService(){ 8 ltos = new HashMap<String, Integer>(); 9 stol = new HashMap<Integer, String>(); 10 COUNTER = 1; 11 elements = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 12 } 13 14 public String longToShort(String url){ 15 String shortUrl = base10ToBase62(COUNTER); 16 COUNTER++; 17 ltos.put(url, COUNTER); 18 stol.put(COUNTER, url); 19 return "http://tinyurl.com/" + shortUrl; 20 } 21 22 public String shortToLong(String url){ 23 url = url.substring("http://tiny.url/".length()); 24 int n = base62ToBase10(url); 25 return stol.get(n); 26 } 27 28 private int base62ToBase10(String s){ 29 int n = 0; 30 for(int i = 0; i<s.length(); i++){ 31 n = n*62 + convert(s.charAt(i)); 32 } 33 return n; 34 } 35 36 private int convert(char c){ 37 if(c>='0' && c<='9'){ 38 return c-'0'; 39 }else if(c>='a' && c<='z'){ 40 return c-'a'+10; 41 }else if(c>='A' && c<='Z'){ 42 return c-'A'+36; 43 } 44 45 return -1; 46 } 47 48 private String base10ToBase62(int n){ 49 StringBuilder sb = new StringBuilder(); 50 while(n != 0){ 51 sb.insert(0, elements.charAt(n%62)); 52 n /= 62; 53 } 54 55 while(sb.length() != 6){ 56 sb.insert(0, '0'); 57 } 58 59 return sb.toString(); 60 } 61 }?
轉載于:https://www.cnblogs.com/Dylan-Java-NYC/p/7776511.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的LeetCode Design TinyURL的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 程序通过定义学生结构体变量,存储学生的学
- 下一篇: Hadoop学习笔记—1.基本介绍与环境