【每日一题Day92】LC2299强密码检验器 II | 模拟 状态压缩

强密码检验器 II【LC2299】

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.

  • 思路:首先判断密码长度是否大于等于8,若是则判断该密码是否包含至少一个数字、小写字母、大写字母以及特殊字符,并相邻字符不相同,若满足条件则返回true。

  • 实现:使用一个变量记录该密码是否包含数字、小写字母、大写字母以及特殊字符,若都包含则返回true。

    class Solution {
        public boolean strongPasswordCheckerII(String password) {
            int n = password.length();
            if (n < 8){
                return false;
            }
            int flag = 0;
            for (int i = 0; i < password.length(); i++){
                char c = password.charAt(i);
                if (i > 0 && password.charAt(i - 1) == c){
                    return false;
                }
                if ( c >= '0' && c <= '9'){
                    flag |= 1 << 0;
                }else if ( c >= 'a' && c <= 'z'){
                    flag |= 1 << 1;
                }else if ( c >= 'A' && c <= 'Z'){
                    flag |= 1 << 2;
                }else{
                    flag |= 1 << 3;
                }
            }
            return flag >= 15;
        }
        
    }
    
    • 复杂度分析

      • 时间复杂度: O ( n ) O(n) O(n)
      • 空间复杂度: O ( 1 ) O(1) O(1)

你可能感兴趣的:(每日一题,位运算,模拟,leetcode,java,算法)