设计一个验证系统
发布日期:2021-05-08 00:00:39 浏览次数:14 分类:精选文章

本文共 1833 字,大约阅读时间需要 6 分钟。

原题指路

题目描述

你需要设计一个包含验证码的验证系统。每一次验证中,用户会收到一个新的验证码,这个验证码在 currentTime 时刻之后 timeToLive 秒过期。如果验证码被更新了,那么它会在 currentTime (可能与之前的 currentTime 不同)时刻延长 timeToLive 秒。

请你实现 AuthenticationManager 类:

AuthenticationManager(int timeToLive) 构造 AuthenticationManager 并设置 timeToLive 参数。

generate(string tokenId, int currentTime) 给定 tokenId ,在当前时间 currentTime 生成一个新的验证码。
renew(string tokenId, int currentTime) 将给定 tokenId未过期 的验证码在 currentTime 时刻更新。如果给定 tokenId 对应的验证码不存在或已过期,请你忽略该操作,不会有任何更新操作发生。
countUnexpiredTokens(int currentTime) 请返回在给定 currentTime 时刻,未过期 的验证码数目。
如果一个验证码在时刻 t 过期,且另一个操作恰好在时刻 t 发生(renew 或者 countUnexpiredTokens 操作),过期事件 优先于 其他操作。

解题思路

图片1.png

这道题其实最重要的一点就是为验证码的保存建立一个键值对的表,以便于验证码的各种更新与维护操作。在使用C++编程的时候,可以调用STL中的map模板来进行模拟。

代码

class AuthenticationManager {       private:        int ttl;        map
token; public: AuthenticationManager(int timeToLive) { ttl = timeToLive; } void generate(string tokenId, int currentTime) { token[tokenId] = currentTime + ttl; } void renew(string tokenId, int currentTime) { if(token.count(tokenId)) if(token[tokenId] > currentTime) token[tokenId] = currentTime + ttl; } int countUnexpiredTokens(int currentTime) { int cnt = 0; map
::iterator it; for(it = token.begin(); it != token.end(); it++) if(it->second > currentTime) cnt++; return cnt; }};/** * 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); */
上一篇:积压订单中的订单总数
下一篇:最大升序子数组和

发表评论

最新留言

不错!
[***.144.177.141]2025年03月19日 19时33分53秒