Leetcode 2299. Strong Password Checker II
Leetcode Problem 2299: Strong Password Checker II
A password is considered strong if the below conditions are all met:
!@#$%^&*()-+
Given a string password, return true
if it is a strong password. Otherwise, return false
.
!@#$%^&*()-+
?
false
.true
; otherwise, return false
.public class StrongPasswordChecker {
public boolean strongPasswordCheckerII(String password) {
if (password.length() < 8) return false;
boolean hasLowerCase = false;
boolean hasUpperCase = false;
boolean hasDigit = false;
boolean hasSpecialChar = false;
String specialCharacters = "!@#$%^&*()-+";
for (int i = 0; i < password.length(); i++) {
char ch = password.charAt(i);
// Check for lowercase letter
if (Character.isLowerCase(ch)) {
hasLowerCase = true;
}
// Check for uppercase letter
if (Character.isUpperCase(ch)) {
hasUpperCase = true;
}
// Check for digit
if (Character.isDigit(ch)) {
hasDigit = true;
}
// Check for special character
if (specialCharacters.indexOf(ch) != -1) {
hasSpecialChar = true;
}
// Check for the same character in adjacent positions
if (i > 0 && ch == password.charAt(i - 1)) {
return false;
}
}
return hasLowerCase && hasUpperCase && hasDigit && hasSpecialChar;
}
}
Time Complexity: O(n), where n is the length of the password. We traverse the password once to check all conditions, making the operations linear with respect to the length of the password.
Space Complexity: O(1). We use a fixed amount of extra space for variables and the special characters string, regardless of the input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?