Untitled
unknown
c_cpp
2 years ago
1.8 kB
11
Indexable
#include <vector>
#include <string>
#include <unordered_map>
#include <sstream>
#include <iostream>
using namespace std;
vector<int> getUnexpiredTokens(int time_to_live, const vector<string>& queries) {
class TokenManager {
unordered_map<string, int> tokens; // stores token_id and its expiry time.
int ttl;
public:
TokenManager(int time_to_live) : ttl(time_to_live) {}
void generate(const string& token_id, int current_time) {
tokens[token_id] = current_time + ttl;
}
void renew(const string& token_id, int current_time) {
if(tokens.find(token_id) != tokens.end() && tokens[token_id] > current_time) {
tokens[token_id] = current_time + ttl;
}
}
int count(int current_time) {
int count = 0;
for(auto it = tokens.begin(); it != tokens.end();) {
if(it->second <= current_time) {
it = tokens.erase(it);
} else {
count++;
++it;
}
}
return count;
}
};
TokenManager tm(time_to_live);
vector<int> results;
for(const string& query : queries) {
stringstream ss(query);
string type, token_id;
int current_time;
ss >> type;
if(type == "generate") {
ss >> token_id >> current_time;
tm.generate(token_id, current_time);
} else if(type == "renew") {
ss >> token_id >> current_time;
tm.renew(token_id, current_time);
} else if(type == "count") {
ss >> current_time;
results.push_back(tm.count(current_time));
}
}
return results;
}Editor is loading...