1. 程式人生 > >Encode and Decode TinyURL

Encode and Decode TinyURL

ins def str repl 服務 returns -a 做了 abcdefg

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.

想了下可能的重復編碼問題,直接用HashMap做了短URL和長URL的映射.將數字和字母混合編碼,按題目的6位數的編碼的話可以達到\(36^6\)種編碼,理論上性能是ok的.
代碼如下

public class Codec {

    HashMap<String, String> enIndex = new HashMap<String, String>();
    HashMap<String,String>deIndex = new HashMap<String, String>();
    String keyset = "0123456789abcdefghijklmnopqrstuvwyz"
; String tinyUrlBase = "http://tinyurl.com/"; // Encodes a URL to a shortened URL. public String encode(String longUrl) { String key; if (enIndex.containsKey(longUrl)) return enIndex.get(longUrl); do{ StringBuilder sb = new StringBuilder(); for
(int i =0 ; i<6;i++){ sb.append(keyset.charAt((int) (Math.random()*keyset.length()))); } key = sb.toString(); }while(deIndex.containsKey(key)); deIndex.put(key,longUrl); enIndex.put(longUrl, tinyUrlBase+key); return tinyUrlBase+key; } // Decodes a shortened URL to its original URL. public String decode(String shortUrl) { return deIndex.get(shortUrl.replace(tinyUrlBase,"")); } }

寫完看了下排名.....貌似蠻低的.不過這題感覺是比較自由,應該不會太卡時間的,感覺就是考慮怎麽編碼好點.
前面的方案大致有:

  1. 用計數器編碼
    那麽當前服務器存了多少url就曝露出來了,也許會有安全隱患。而且計數器編碼另一個缺點就是數字會不斷的增大
  2. 直接返回參數(最快)
    ....這道題的OJ基本上是形同虛設,兩個函數分別直接返回參數字符串也能通過OJ,囧

Encode and Decode TinyURL