LeetCode 题解工作台
强密码检验器 II
如果一个密码满足以下所有条件,我们称它是一个 强 密码: 它有至少 8 个字符。 至少包含 一个小写英文 字母。 至少包含 一个大写英文 字母。 至少包含 一个数字 。 至少包含 一个特殊字符 。特殊字符为: "!@#$%^&*()-+" 中的一个。 它 不 包含 2 个连续相同的字符(比方说 "a…
1
题型
7
代码语言
3
相关题
当前训练重点
简单 · String-driven solution strategy
答案摘要
根据题目描述,我们可以模拟检查密码是否满足题目要求的过程。 首先,我们检查密码的长度是否小于 ,如果是,则返回 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
如果一个密码满足以下所有条件,我们称它是一个 强 密码:
- 它有至少
8个字符。 - 至少包含 一个小写英文 字母。
- 至少包含 一个大写英文 字母。
- 至少包含 一个数字 。
- 至少包含 一个特殊字符 。特殊字符为:
"!@#$%^&*()-+"中的一个。 - 它 不 包含
2个连续相同的字符(比方说"aab"不符合该条件,但是"aba"符合该条件)。
给你一个字符串 password ,如果它是一个 强 密码,返回 true,否则返回 false 。
示例 1:
输入:password = "IloveLe3tcode!" 输出:true 解释:密码满足所有的要求,所以我们返回 true 。
示例 2:
输入:password = "Me+You--IsMyDream" 输出:false 解释:密码不包含数字,且包含 2 个连续相同的字符。所以我们返回 false 。
示例 3:
输入:password = "1aB!" 输出:false 解释:密码不符合长度要求。所以我们返回 false 。
提示:
1 <= password.length <= 100password包含字母,数字和"!@#$%^&*()-+"这些特殊字符。
解题思路
方法一:模拟 + 位运算
根据题目描述,我们可以模拟检查密码是否满足题目要求的过程。
首先,我们检查密码的长度是否小于 ,如果是,则返回 。
接下来,我们用一个掩码 来记录密码是否包含小写字母、大写字母、数字和特殊字符。我们遍历密码,每次遍历到一个字符,先判断它是否和前一个字符相同,如果是,则返回 。然后,根据字符的类型更新掩码 。最后,我们检查掩码 是否为 ,如果是,则返回 ,否则返回 。
时间复杂度 ,空间复杂度 。其中 为密码的长度。
class Solution:
def strongPasswordCheckerII(self, password: str) -> bool:
if len(password) < 8:
return False
mask = 0
for i, c in enumerate(password):
if i and c == password[i - 1]:
return False
if c.islower():
mask |= 1
elif c.isupper():
mask |= 2
elif c.isdigit():
mask |= 4
else:
mask |= 8
return mask == 15
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for a solution that efficiently checks each condition while maintaining clarity.
- question_mark
Candidates should avoid unnecessary loops and optimize string traversal.
- question_mark
Watch for candidates who struggle with the adjacency check, as this could indicate a misunderstanding of the requirements.
常见陷阱
外企场景- error
Failing to handle all the character types correctly, especially when characters like special symbols are overlooked.
- error
Not checking for adjacent identical characters, which is a critical part of the problem.
- error
Overcomplicating the solution with multiple nested loops or excessive space complexity.
进阶变体
外企场景- arrow_right_alt
Modify the problem to require a minimum of two special characters.
- arrow_right_alt
Change the password rules to allow only certain special characters (e.g., only '@' or '!').
- arrow_right_alt
Allow passwords of length 6 or more, testing if the solution scales with different constraints.