这是第22篇算法,力扣链接
你需要设计一个包含验证码的验证系统。每一次验证中,用户会收到一个新的验证码,这个验证码在
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:
输入: ["AuthenticationManager", "renew
", "generate", "countUnexpiredTokens
", "generate", "renew
", "renew
", "countUnexpiredTokens
"] [[5], ["aaa", 1], ["aaa", 2], [6], ["bbb", 7], ["aaa", 8], ["bbb", 10], [15]] 输出: [null, null, null, 1, null, null, null, 0] 解释: AuthenticationManager authenticationManager = new AuthenticationManager(5); // 构造 AuthenticationManager ,设置timeToLive
= 5 秒。 authenticationManager.renew
("aaa", 1); // 时刻 1 时,没有验证码的 tokenId 为 "aaa" ,没有验证码被更新。 authenticationManager.generate("aaa", 2); // 时刻 2 时,生成一个 tokenId 为 "aaa" 的新验证码。 authenticationManager.countUnexpiredTokens
(6); // 时刻 6 时,只有 tokenId 为 "aaa" 的验证码未过期,所以返回 1 。 authenticationManager.generate("bbb", 7); // 时刻 7 时,生成一个 tokenId 为 "bbb" 的新验证码。 authenticationManager.renew
("aaa", 8); // tokenId 为 "aaa" 的验证码在时刻 7 过期,且 8 >= 7 ,所以时刻 8 的renew 操作被忽略,没有验证码被更新。 authenticationManager.renew
("bbb", 10); // tokenId 为 "bbb" 的验证码在时刻 10 没有过期,所以 renew 操作会执行,该 token 将在时刻 15 过期。 authenticationManager.countUnexpiredTokens
(15); // tokenId 为 "bbb" 的验证码在时刻 15 过期,tokenId 为 "aaa" 的验证码在时刻 7 过期,所有验证码均已过期,所以返回 0 。
这道题看起来很复杂,不过其实静下心来这就是再简单不过的业务逻辑罢了。一共四个方法,各司其职。
首先思考构造器方法,这里固定的是过期时间,每一个tokenId对应一个开始时间,开始时间+过期时间对比当前时间来判断是否过期。
没什么额外讲的,直接上代码:
type AuthenticationManager struct {
tokenMap map[string]int
timeToLive int
}
func Constructor(timeToLive int) AuthenticationManager {
return AuthenticationManager{
make(map[string]int), timeToLive,
}
}
func (this *AuthenticationManager) Generate(tokenId string, currentTime int) {
this.tokenMap[tokenId] = currentTime
}
func (this *AuthenticationManager) Renew(tokenId string, currentTime int) {
if tokenTime, ok := this.tokenMap[tokenId]; ok {
if tokenTime+this.timeToLive > currentTime {
this.tokenMap[tokenId] = currentTime
}
}
}
func (this *AuthenticationManager) CountUnexpiredTokens(currentTime int) int {
result := 0
for _, tokenTime := range this.tokenMap {
if tokenTime+this.timeToLive > currentTime {
result++
}
}
return result
}