aboutsummaryrefslogtreecommitdiff
path: root/encode_decode_tinyurl.cpp
blob: 7596c6a8c8b11e30afe1df44e04eb68ed2066a2d (plain)
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
#include "leetcode.h"

class Solution {
public:
  unordered_map<string, string> codeDB, urlDB;
  const string chars =
      "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  string encode(string longUrl) {
    if (urlDB.find(longUrl) != urlDB.end())
      return urlDB[longUrl];
    string code = genCode();
    while (codeDB.find(code) != codeDB.end())
      code = genCode();
    codeDB[code] = longUrl;
    urlDB[longUrl] = code;
    return code;
  }
  string decode(string shortUrl) { return codeDB[shortUrl]; }

private:
  string genCode() {
    string code = "";
    for (int i = 0; i < 6; i++)
      code += chars[rand() % 62];
    return "http://tinyurl.com/" + code;
  }
};

int main() {}