carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode2299: Strong Password Checker II #377

Open carloscn opened 11 months ago

carloscn commented 11 months ago

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

carloscn commented 11 months ago

Analysis

static int32_t strongPasswordCheckerII(const char *password, bool *result)
{
    int32_t ret = 0;
    size_t len;

    UTILS_CHECK_PTR(password);
    UTILS_CHECK_PTR(result);
    UTILS_CHECK_LEN(len = strlen(password));

    if (len < 8) {
        *result = false;
        goto finish;
    }

    uint8_t flag = 0;
    for (size_t i = 0; i < len; i ++) {
        if (islower(password[i])) {
            flag |= 1;
        } else if (isupper(password[i])) {
            flag |= 1 << 1;
        } else if (isdigit(password[i])) {
            flag |= 1 << 2;
        } else if (ispunct(password[i])) {
            flag |= 1 << 3;
        }
        if (i < len && password[i] == password[i + 1]) {
            *result = false;
            goto finish;
        }
    }

    if (flag != 0x0Fu) {
        *result = false;
        goto finish;
    }

finish:
    return ret;
}
carloscn commented 11 months ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1170567 https://github.com/carloscn/structstudy/commit/aefd1c8141d0ac46f4208f7301fe84eedfae2520