TinyURL 的加密與解密

題目鏈接:https://leetcode-cn.com/problems/encode-and-decode-tinyurl/description/

該題是hash表的一種應用。

隨機固定長度加密 ,在這種方法中,使用數字和字母表集合來爲 URL 生成加密結果。這種方法中,加密後的長度固定是 6 位。如果產生出來的加密結果與之前產生的結果一樣,就換一個新的加密結果。

public class Codec {
    
    String alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    HashMap<String,String> map = new HashMap<>();
    Random random = new Random();
    String key = getString();


    public String getString(){
     
     StringBuilder sb = new StringBuilder();
     for(int i = 0;i < 6;i++){
         sb.append(alphabet.charAt(random.nextInt(62)));
     }
     return sb.toString();
    } 


    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        if(map.containsKey(key)){
            key = getString();
        }
        map.put(key,longUrl);

        return "http://tinyurl.com/"+key;
    }

    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
        return map.get(shortUrl.replace("http://tinyurl.com/",""));
    }
}

 

表現分析
1.可加密的 URL 數目非常大,幾乎是 (10 + 26*2)^6級別。

2.加密 URL 的長度固定是 6,這相比於能加密的字符串數目是極大的縮減優化。

3.這個方法的表現非常好,因爲幾乎不可能產生相同加密結果。

4.我們也可以通過增加加密字符串的長度來增加加密結果的數目。因此,在加密字符串的長度和可加密的字符串數目之間我們需要做一個權衡。

5.根據加密 URL 預測加密結果幾乎是不可能的,因爲使用了隨機數。

發佈了65 篇原創文章 · 獲贊 13 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章