这个题目如果自己写一个算法的话确实很难,但是这个是没有什么要求的,因此就简单多了。最简单的就是不做任何处理,直接返回
class Solution {
public:
// Encodes a URL to a shortened URL.
string encode(string longUrl) {
return longUrl;
}
// Decodes a shortened URL to its original URL.
string decode(string shortUrl) {
return shortUrl;
}
};
但是这种解法很无聊,因此我用了一种简单映射的方法来实现,设置一个count用来保证不同url的不同id。
class Solution {
public:
map<string,string> m;
int count=0;
// Encodes a URL to a shortened URL.
string encode(string longUrl) {
string shortUrl=to_string(count);
m.insert(pair<string,string>(shortUrl,longUrl));
count++;
return shortUrl;
}
// Decodes a shortened URL to its original URL.
string decode(string shortUrl) {
return m[shortUrl];
}
};