原题链接:
https://leetcode.cn/problems/design-authentication-manager/
理解题意:
-
timeToLive
为token
的有效时间长度 -
currentTime + timeToLive
为token
的到期时间 - 如果当前时间超过了缓存的到期时间,即为过期
解题思路:
- 使用
Map
缓存token
及其到期时间 - 执行
generate
时,将token
和到期时间currentTime + timeToLive
缓存 - 执行
renew
时,查看token
的到期时间是否超过了当前时间,未超过表示还未过期,为token
设置新的到期时间 - 执行
countUnexpiredTokens
时,统计Map
中缓存的token
到期时间大于当前时间,即未过期的token
数量
/**
* @param {number} timeToLive
*/
var AuthenticationManager = function(timeToLive) {
this.timeToLive = timeToLive // 有效时间
this.map = new Map() // 缓存token和过期时间
};
/**
* @param {string} tokenId
* @param {number} currentTime
* @return {void}
*/
AuthenticationManager.prototype.generate = function(tokenId, currentTime) {
// 每次创建时,保存tokenId和过期时间
// 过期时间为当前时间加上有效时间
this.map.set(tokenId, currentTime + this.timeToLive)
};
/**
* @param {string} tokenId
* @param {number} currentTime
* @return {void}
*/
AuthenticationManager.prototype.renew = function(tokenId, currentTime) {
// 如果当前token还未到过期时间,就设置新过期时间为当前时间加上有效时间
if (this.map.get(tokenId) > currentTime) {
this.map.set(tokenId, currentTime + this.timeToLive)
}
};
/**
* @param {number} currentTime
* @return {number}
*/
AuthenticationManager.prototype.countUnexpiredTokens = function(currentTime) {
let count = 0 // 存储未过期验证码数量
// 遍历所有过期时间
for (const time of this.map.values()) {
// 如果当前时间还未到过期时间,就进行计数
if (time > currentTime) {
count++
}
}
return count
};
/**
* Your AuthenticationManager object will be instantiated and called as such:
* var obj = new AuthenticationManager(timeToLive)
* obj.generate(tokenId,currentTime)
* obj.renew(tokenId,currentTime)
* var param_3 = obj.countUnexpiredTokens(currentTime)
*/