[Leetcode] 535. Encode and Decode tinyurl encoding and decoding short URLs

Source: Internet
Author: User

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 Retu RNs A short URL such as Http://tinyurl.com/4e9iAk.

Design the Encode and decode methods for the TinyURL service. There is no restriction on what your encode/decode algorithm should work. You just need to ensure, that a URL can is encoded to a tiny URL and the tiny URL can is decoded to the original URL.

C++:

Class Solution {Public:solution () {dict = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";        Short2long.clear ();        Long2short.clear ();    Srand (Time (NULL));    }//encodes a URL to a shortened URL. String encode (string longurl) {if (Long2short.count (Longurl)) {return ' http://tinyurl.com/' + Long2sho        Rt[longurl];        } int idx = 0;        String Randstr;        for (int i = 0; i < 6; ++i) Randstr.push_back (Dict[rand ()% 62]);            while (Short2long.count (RANDSTR)) {Randstr[idx] = Dict[rand ()% 62];        IDX = (idx + 1)% 5;        } Short2long[randstr] = Longurl;        Long2short[longurl] = randstr;    Return "http://tinyurl.com/" + randstr;    }//decodes a shortened URL to its original URL.        String decode (String shorturl) {string randstr = Shorturl.substr (shorturl.find_last_of ("/") + 1); Return Short2long.count (RANDSTR)? SHORT2LONG[RANDSTR]: Shorturl;    } private:unordered_map<string, string> Short2long, Long2short; string dict;};

  

[Leetcode] 535. Encode and Decode tinyurl encoding and decoding short URLs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.