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

24 阅读1分钟

原题链接: leetcode.cn/problems/de…

理解题意:

  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
};