为确保用户安全,网站将对用户在注册时设置的密码进行密码强度验证。
强密码必须遵守所有规则
同一个字符不能连续出现三次。
密码的长度必须在8到22个字符之间。
密码必须至少包含一个小写字母和一个大写字母和一个数字。
如果给定密码为强,则返回“strong”,否则返回“weak”。
请注意,请不要返回true或false。
/*Example 1:
Input: password = "1234567890Abcd"
Output: "strong"
Example 2:
Input: password = "1234567890aaaa"
Output: "weak"
Example 3:Input: password = "1234567890abcd"
Output: "weak"*/
public static boolean validate(String password) {
// 检查密码长度
if (password.length() < 8 || password.length() > 22) {
return "weak";
}
// 检查同一个字符是否连续出现三次
for (int i = 0; i < password.length() - 2; i++) {
if (password.charAt(i) == password.charAt(i + 1) && password.charAt(i) == password.charAt(i + 2)) {
return "weak";
}
}
// 检查密码是否至少包含一个小写字母,一个大写字母和一个数字
boolean hasLowerCase = false, hasUpperCase = false, hasDigit = false;
for (int i = 0; i < password.length(); i++) {
char ch = password.charAt(i);
if (Character.isLowerCase(ch)) {
hasLowerCase = true;
} else if (Character.isUpperCase(ch)) {
hasUpperCase = true;
} else if (Character.isDigit(ch)) {
hasDigit = true;
}
if (hasLowerCase && hasUpperCase && hasDigit) {
return "strong";
}
}
return "weak";
}