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