设计一个验证系统
-
分析
- 给定tokenId,currentTime以及timeToLive,我们定义一个字典,存储的形式为dict[tokenId] = currentTime + timeToLive.
- 在renew函数中,判断一下tokenId是否在字典的键中以及对应的值是否小于currentTime,如果都成立,则重置验证码,即dict[tokenId] = currentTime + timeToLive. 否则什么也不做。
- 在countUnexpiredTokens函数中,定义一个变量res = 0, 依次遍历字典,如果字典中的值小于给定的currentTime,则res ++, 否则什么也不做。
- 最后返回res即可。
-
代码:
- C++代码
class AuthenticationManager { public: int timeToLive; unordered_map<string, int> mp; AuthenticationManager(int timeToLive) { this->timeToLive = timeToLive; } void generate(string tokenId, int currentTime) { mp[tokenId] = currentTime + timeToLive; } void renew(string tokenId, int currentTime) { if (mp.count(tokenId) && mp[tokenId] > currentTime){ mp[tokenId] = currentTime + timeToLive; } } int countUnexpiredTokens(int currentTime) { int res = 0; for(auto &[_, time]: mp){ if (time > currentTime) { res ++; } } return res; } }; /** * Your AuthenticationManager object will be instantiated and called as such: * AuthenticationManager* obj = new AuthenticationManager(timeToLive); * obj->generate(tokenId,currentTime); * obj->renew(tokenId,currentTime); * int param_3 = obj->countUnexpiredTokens(currentTime); */
- python代码:
class AuthenticationManager: def __init__(self, timeToLive: int): self.timeToLive = timeToLive self.mp = dict() def generate(self, tokenId: str, currentTime: int) -> None: self.mp[tokenId] = currentTime + self.timeToLive def renew(self, tokenId: str, currentTime: int) -> None: if tokenId in self.mp and self.mp[tokenId] > currentTime: self.mp[tokenId] = currentTime + self.timeToLive def countUnexpiredTokens(self, currentTime: int) -> int: res = 0 for _, time in self.mp.items(): if time > currentTime: res += 1 return res # Your AuthenticationManager object will be instantiated and called as such: # obj = AuthenticationManager(timeToLive) # obj.generate(tokenId,currentTime) # obj.renew(tokenId,currentTime) # param_3 = obj.countUnexpiredTokens(currentTime)
-
分析
- 使用哈希表较为方便;
- 模拟题。
网友评论