top of page

2299. Strong Password Checker II

Overall

Introduction

When we register the account of website such as Facebook, Twitter and Google. The website always require us that we need set a strong password. Otherwise we cannot complete the register. Now this Leetcode problem can help us to understand that how the website check the password is a strong password.

Problem Content

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

Concept

The problem set the password has at least 8 characters. Therefore we check the password length first. If the password length is lower than 8, we do not need check other thing then return false directly.

​

Next, the password require at least one lowercase letter, one uppercase letter, one digit and at least one of "!@#$%^&*()-+". We can use

regex test("/[a-z]/.test(password) && /[A-Z]/.test(password)&& /[-!@#$%^&*()+]/.test(password)&& /[0-9]/.test(password)") with boolean to check the password include above these.

​

If the password pass above require, the final criteria is not contain 2 of the same character in adjacent positions(e.g. "aab"). We use for loop to check the next character is not equal the current character.


The password is strong password if it can pass all of these criteria.

Solve(Javascript)

/**
* @param {string} password
* @return {boolean}
*/
var strongPasswordCheckerII = function(password) {
    let len=password.length;
    let lc=/[a-z]/.test(password) && /[A-Z]/.test(password)&& /[-!@#$%^&*()+]/.test(password)&& /[0-9]/.test(password);

​

    if(len<8){
        return false;
        }


    for(let i=0;i<len-1;i++){

       if(password[i]==password[i+1]){

           return false;
           }

        
        }
    return lc;
};

bottom of page