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.Solution in C++:
class Solution {
public:
map<string, string> url;
// Encodes a URL to a shortened URL.
string encode(string longUrl) {
static int count = 0;
char *a = (char*)calloc(sizeof(char), 30);
++count;
sprintf(a,"%s%d","https://tinyurl.com/",count);
url.insert({a, longUrl});
return a;
}
// Decodes a shortened URL to its original URL.
string decode(string shortUrl) {
auto temp = url.find(shortUrl);
if(temp != url.end()){
return temp->second;
}
return nullptr;
}
};
public:
map<string, string> url;
// Encodes a URL to a shortened URL.
string encode(string longUrl) {
static int count = 0;
char *a = (char*)calloc(sizeof(char), 30);
++count;
sprintf(a,"%s%d","https://tinyurl.com/",count);
url.insert({a, longUrl});
return a;
}
// Decodes a shortened URL to its original URL.
string decode(string shortUrl) {
auto temp = url.find(shortUrl);
if(temp != url.end()){
return temp->second;
}
return nullptr;
}
};
Comments
Post a Comment