2299. Strong Password Checker II

Question

A password is said to be strong if it satisfies all the following criteria:

  • It has at least 8 characters.

  • 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 2 of 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 a strong password*. Otherwise, return false.

Solution

直接遍历,记录四个真值对应四个符号,初始化为false,和上一个字符last。
每次遍历检查当前字符,如果等于上个字符则直接返回false。
根据字符范围来改变四个真值,最后返回四个真值的和运算。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public boolean strongPasswordCheckerII(String password) {
if(password.length() < 8) return false;
char last = ' ';
boolean hasLower = false, hasUpper = false, hasDigit = false, hasSpecial = false;
char[] word = password.toCharArray();

for(int i = 0; i < password.length(); i++){
char cur = word[i];
if(last == cur) return false;
if(cur >= 'a' && cur <= 'z') hasLower = true;
else if(cur >= 'A' && cur <= 'Z') hasUpper = true;
else if(cur >= '0' && cur <= '9') hasDigit = true;
else hasSpecial = true;
last = cur;
}

return hasLower && hasUpper && hasDigit && hasSpecial;
}
}
Author

Xander

Posted on

2022-06-12

Updated on

2022-06-11

Licensed under

Comments