zoukankan      html  css  js  c++  java
  • [LeetCode] 535. Encode and Decode TinyURL 编码和解码短网址

    Note: This is a companion problem to the System Design problem: Design 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.

    Python:

    class Codec:
        def __init__(self):
            self.__random_length = 6
            self.__tiny_url = "http://tinyurl.com/"
            self.__alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
            self.__lookup = {}
    
        def encode(self, longUrl):
            """Encodes a URL to a shortened URL.
            
            :type longUrl: str
            :rtype: str
            """
            def getRand():
                rand = []
                for _ in xrange(self.__random_length):
                    rand += self.__alphabet[random.randint(0, len(self.__alphabet)-1)]
                return "".join(rand)
            
            key = getRand()
            while key in self.__lookup:
                key = getRand()
            self.__lookup[key] = longUrl
            return self.__tiny_url + key
    
        def decode(self, shortUrl):
            """Decodes a shortened URL to its original URL.
            
            :type shortUrl: str
            :rtype: str
            """
            return self.__lookup[shortUrl[len(self.__tiny_url):]]

     Python:Using sha256

    from hashlib import sha256
    
    class Codec:
    
        def __init__(self):
            self._cache = {}
            self.url = 'http://tinyurl.com/'
    
        def encode(self, long_url):
            """Encodes a URL to a shortened URL.
            :type long_url: str
            :rtype: str
            """
            key = sha256(long_url.encode()).hexdigest()[:6]
            self._cache[key] = long_url
            return self.url + key
    
        def decode(self, short_url):
            """Decodes a shortened URL to its original URL.
            :type short_url: str
            :rtype: str
            """
            key = short_url.replace(self.url, '')
            return self._cache[key]
    

    C++:

    class Solution {
    public:
        Solution() : gen_((random_device())()) {
        }
    
        // Encodes a URL to a shortened URL.
        string encode(string longUrl) {
            string key = getRand();
            while (lookup_.count(key)) {
                key = getRand();
            }
            lookup_[key] = longUrl;
            return "http://tinyurl.com/" + key;
        }
    
        // Decodes a shortened URL to its original URL.
        string decode(string shortUrl) {
            return lookup_[shortUrl.substr(tiny_url.length())];
        }
    
    private:
        string getRand() {
            string random;
            for (int i = 0; i < random_length; ++i) {
                random += alphabet_[uniform_int_distribution<int>{0, alphabet_.length() - 1}(gen_)];
            }
            return random;
        }
    
        const int random_length = 6;
        const string tiny_url = "http://tinyurl.com/";
        const string alphabet_ = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        default_random_engine gen_;
        unordered_map<string, string> lookup_;
    };
    

      

    类似题目:

    [LeetCode] 534. Design TinyURL 设计短网址

    All LeetCode Questions List 题目汇总

      

  • 相关阅读:
    Axure案例:用中继器实现便捷好用的3级菜单--转载
    我说CMMI之七:需求管理过程域--转载
    我说CMMI之六:CMMI的评估--转载
    我说CMMI之五:CMMI 4个等级的区别--转载
    我说CMMI之四:CMMI的表示方法--转载
    我说CMMI之三:CMMI的构件--转载
    我说CMMI之二:CMMI里有什么?--转载
    我说CMMI之一:CMMI是什么--转载
    PMBOK :美国的项目管理知识体系
    有关 CMMI
  • 原文地址:https://www.cnblogs.com/lightwindy/p/8481759.html
Copyright © 2011-2022 走看看