1. 程式人生 > >535. Encode and Decode TinyURL(python+cpp)

535. Encode and Decode TinyURL(python+cpp)

題目:

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.

解釋:
用字典儲存shortUrl所對應的 longUrl,shortUrl需要有唯一的標識。
python程式碼:

class Codec:
    def __init__(self):
        self._dict={}
        self.key=0

    def encode(self, longUrl):
        """Encodes a URL to a shortened URL.
        
        :type longUrl: str
        :rtype: str
        """
        txt=
"tinyurl"+str(self.key) self._dict[txt]=longUrl self.key+=1 return txt def decode(self, shortUrl): """Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str """ return self._dict[shortUrl] # Your Codec object will be instantiated and called as such:
# codec = Codec() # codec.decode(codec.encode(url))

c++程式碼:

#include <map>
using namespace std;
class Solution {
public:
    map<string,string> _map;
    int key=0;
    // Encodes a URL to a shortened URL.
    string encode(string longUrl) {
        string txt="tinyurl"+to_string(key);
        _map[txt]=longUrl;
        key++;
        return txt;
    }

    // Decodes a shortened URL to its original URL.
    string decode(string shortUrl) {
        return _map[shortUrl];
    }
};

// Your Solution object will be instantiated and called as such:
// Solution solution;
// solution.decode(solution.encode(url));

總結: