-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
47 lines (41 loc) · 1.15 KB
/
main.cpp
File metadata and controls
47 lines (41 loc) · 1.15 KB
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
44
45
46
#include <iostream>
#include <vector>
#include <unordered_map>
class Solution {
std::unordered_map<std::string, std::string> storage;
std::vector<char> charPool;
public:
Solution() {
std::string s = "qwertyuiopasdfghjklzxcvbnm1234567890";
charPool = std::vector<char> {s.begin(), s.end()};
}
// Encodes a URL to a shortened URL.
std::string encode(std::string longUrl) {
std::string result = "";
do {
result = randomSeq();
} while (storage.count(result) > 0);
storage[result] = longUrl;
return result;
}
std::string randomSeq() {
std::string result = "";
for (int i = 0; i < 6; i++) {
char r = charPool[rand() % charPool.size()];
result += r;
}
return result;
}
// Decodes a shortened URL to its original URL.
std::string decode(std::string shortUrl) {
if (storage.count(shortUrl) > 0) {
return storage[shortUrl];
}
return "";
}
};
int main() {
Solution solution;
std::cout << solution.decode(solution.encode("abc")) << std::endl;
return 0;
}