题目
原题在此
解析
基本是按照这个实现的.
一个随机字符串生成器加map储存.
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| #include <iostream> #include <ctime> #include <unistd.h>
class Solution { public:
string encode(string longUrl) { string str = gen_random(6); while(mp.find(str) != mp.end()) str = gen_random(6); mp[str] = longUrl; return str; }
string decode(string shortUrl) { return mp[shortUrl]; }
private: map<string, string> mp; string gen_random(const int len) { string tmp_s; static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz";
srand( (unsigned) time(NULL) * getpid()); tmp_s.reserve(len); for (int i = 0; i < len; ++i) tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)];
return tmp_s; } };
|