LeetCode 2299. Strong Password Checker II Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
2299. Strong Password Checker II

Description

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.

 

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: "!@#$%^&*()-+".

Solutions

Solution 1: Simulation + Bit Manipulation

According to the problem description, we can simulate the process of checking whether the password meets the requirements.

First, we check if the length of the password is less than 8. If it is, we return false.

Next, we use a mask mask to record whether the password contains lowercase letters, uppercase letters, digits, and special characters. We traverse the password, and for each character, we first check if it is the same as the previous character. If it is, we return false. Then, we update the mask mask based on the character type. Finally, we check if the mask mask is 15. If it is, we return true; otherwise, we return false.

The time complexity is O(n), and the space complexity is O(1). Here, n is the length of the password.

PythonJavaC++GoTypeScriptRustC
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(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !