A password is said to be strong if it satisfies all the following criteria:
8
characters."!@#$%^&*()-+"
.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
.
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 <= 100
password
consists of letters, digits, and special characters: "!@#$%^&*()-+"
.This problem requires checking if a given password meets several criteria: length (at least 8 characters), presence of lowercase, uppercase, digit, and special characters, and the absence of consecutive repeating characters. The solution uses bit manipulation for efficient character type tracking.
The core idea is to use a bitmask to track the presence of different character types. Each bit in the mask represents a character type:
The algorithm iterates through the password string:
Length Check: First, it verifies if the password's length is less than 8. If so, it immediately returns false
.
Consecutive Character Check: During the iteration, it compares each character with the preceding one. If they are identical, it indicates consecutive repetition, and the function returns false
.
Character Type Check: For each character, it checks its type (lowercase, uppercase, digit, or special character) and sets the corresponding bit in the mask
accordingly.
Final Check: After iterating through the entire password, the algorithm checks if the mask
is equal to 15
(binary 1111
). This signifies the presence of all four required character types. If the mask
is 15
, the function returns true
; otherwise, it returns false
.
Time Complexity: O(n), where n is the length of the password string. The algorithm iterates through the string once.
Space Complexity: O(1). The algorithm uses a constant amount of extra space to store the mask
variable, regardless of the input string's length.
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
The code in other languages (Java, C++, Go, TypeScript, Rust, C) follows a very similar structure, adapting syntax and standard library functions appropriately. The core logic of bit manipulation and character type checking remains consistent across all implementations.