2299. 强密码检验器 II
2299. 强密码检验器 II
题目
A password is said to be strong if it satisfies all the following criteria:
- It has at least
8characters. - It contains at least one lowercase letter.
- It contains at least one uppercase letter.
- It contains at least one digit.
- It contains at least one special character. The special characters are the characters in the following string:
"!@#$%^&*()-+". - It does not contain
2of the same character in adjacent positions (i.e.,"aab"violates this condition, but"aba"does not).
Given a string password, return true if it is astrong password. Otherwise, return false.
Example 1:
Input: password = "IloveLe3tcode!"
Output: true
Explanation: The password meets all the requirements. Therefore, we return true.
Example 2:
Input: password = "Me+You--IsMyDream"
Output: false
Explanation: The password does not contain a digit and also contains 2 of the same character in adjacent positions. Therefore, we return false.
Example 3:
Input: password = "1aB!"
Output: false
Explanation: The password does not meet the length requirement. Therefore, we return false.
Constraints:
1 <= password.length <= 100passwordconsists of letters, digits, and special characters:"!@#$%^&*()-+".
题目大意
如果一个密码满足以下所有条件,我们称它是一个 强 密码:
- 它有至少
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包含字母,数字和"!@#$%^&*()-+"这些特殊字符。
解题思路
使用正则表达式来验证是否满足条件。
正则表达式的拆解:
^: 匹配字符串的开始。(?!.*(.)\1): 确保字符串中没有相邻的两个相同字符。.*(.)匹配任意字符后跟一个捕获的字符。\1表示重复捕获的字符。
(?=.*[a-z]): 确保字符串包含至少一个小写字母。(?=.*[A-Z]): 确保字符串包含至少一个大写字母。(?=.*[0-9]): 确保字符串包含至少一个数字。(?=.*[!@#$%^&*()+-]): 确保字符串包含至少一个特殊字符。.{8,}: 确保字符串长度至少为 8。$: 匹配字符串的结尾。
使用
RegExp.prototype.exec()方法匹配正则表达式,返回null表示不符合条件。
复杂度分析
- 时间复杂度:
O(n),正则表达式匹配操作对长度为n的字符串需线性扫描。 - 空间复杂度:
O(1),使用了固定的正则表达式和一些辅助变量。
代码
/**
* @param {string} password
* @return {boolean}
*/
var strongPasswordCheckerII = function (password) {
const regex = new RegExp(
'^(?!.*(.)\\1)(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()+-]).{8,}$',
'g'
);
return regex.exec(password) !== null;
};
相关题目
| 题号 | 标题 | 题解 | 标签 | 难度 | 力扣 |
|---|---|---|---|---|---|
| 420 | 强密码检验器 | 贪心 字符串 堆(优先队列) | 🔴 | 🀄️ 🔗 | |
| 468 | 验证IP地址 | 字符串 | 🟠 | 🀄️ 🔗 |
