LeetCode题解:1797. 设计一个验证系统,哈希表,JavaScript,详细注释

原题链接:
https://leetcode.cn/problems/design-authentication-manager/

理解题意:

  1. timeToLivetoken的有效时间长度
  2. currentTime + timeToLivetoken的到期时间
  3. 如果当前时间超过了缓存的到期时间,即为过期

解题思路:

  1. 使用Map缓存token及其到期时间
  2. 执行generate时,将token和到期时间currentTime + timeToLive缓存
  3. 执行renew时,查看token的到期时间是否超过了当前时间,未超过表示还未过期,为token设置新的到期时间
  4. 执行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)
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值