Problem Description:
TinyURL is a URL shortening service where you enter a URL such as and https://leetcode.com/problems/design-tinyurl
it returns a short URL such as http://tinyurl.com/4e9iAk
.
Design the and methods for the encode
decode
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.
Problem Solving Ideas:
I can think of HashMap, but I don't have any good solution to the problem of collisions, seeing that I want to convert the long into short.
See the analysis of the Grandyang.
This uses the rand () function to randomly generate and get the characters from the dictionary.
After the 6-bit string has been generated, you need to check for collisions and regenerate if a collision occurs.
Two hashmap are used to store:
Short2long: Mainly used for conversion
Long2short: Mainly used to check the weight
Code:
classSolution { Public: Solution () {Dict="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; Short2long.clear (); Long2short.clear (); Srand (Time (NULL)); } //encodes a URL to a shortened URL. stringEncodestringLongurl) { if(Long2short.count (longurl))return "http://tinyurl.com/"+Long2short[longurl]; stringRandstr; for(inti =0; I <6; i++) {Randstr.push_back (Dict[rand ()% +]); } intIDX =0; while(Short2long.count (RANDSTR)) {idx%=6; RANDSTR[IDX]= Dict[rand ()% +]; } Short2long[randstr]=Longurl; Long2short[longurl]=Randstr; return "http://tinyurl.com/"+Randstr; } //decodes a shortened URL to its original URL. stringDecodestringShorturl) { stringRandstr = Shorturl.substr (shorturl.find_last_of ("/")+1); returnShort2long.count (RANDSTR)?Short2long[randstr]: shorturl; }Private: Unordered_map<string,string>Short2long, Long2short; stringdict;};//Your Solution Object would be instantiated and called as such://solution solution;//solution.decode (Solution.encode (URL));
535. Encode and Decode TinyURL