[LeetCode] Encode and Decode TinyURL

來源:互聯網
上載者:User

標籤:tiny   problems   where   algorithm   shorturl   ret   cal   its   ant   

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.

encode: 將longUrl壓入棧中,並將longUrl尾碼轉換為數字加入到tinyurl的尾碼。

decode: 找出tinyurl的尾碼數字,返回棧中數字對應的longUrl.

class Solution {public:    vector<string> urls;    // Encodes a URL to a shortened URL.    string encode(string longUrl) {        urls.push_back(longUrl);        return "http://tinyurl.com/" + to_string(urls.size() - 1);    }    // Decodes a shortened URL to its original URL.    string decode(string shortUrl) {        auto pos = shortUrl.find_last_of(‘/‘);        int num = stoi(shortUrl.substr(pos + 1));        return urls[num];    }};// 3ms// Your Solution object will be instantiated and called as such:// Solution solution;// solution.decode(solution.encode(url));

 

[LeetCode] Encode and Decode TinyURL

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.