Skip to content

2299. Strong Password Checker II 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
 public:
  bool strongPasswordCheckerII(string password) {
    if (password.length() < 8)
      return false;

    const bool hasLowerCase =
        ranges::any_of(password, [](const char c) { return islower(c); });
    if (!hasLowerCase)
      return false;

    const bool hasUpperCase =
        ranges::any_of(password, [](const char c) { return isupper(c); });
    if (!hasUpperCase)
      return false;

    const bool hasDigit =
        ranges::any_of(password, [](const char c) { return isdigit(c); });
    if (!hasDigit)
      return false;

    const bool hasSpecial = ranges::any_of(password, [](const char c) {
      return string("!@#$%^&*()-+").find(c) != string::npos;
    });
    if (!hasSpecial)
      return false;

    for (int i = 1; i < password.length(); ++i)
      if (password[i] == password[i - 1])
        return false;
    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
  public boolean strongPasswordCheckerII(String password) {
    if (password.length() < 8)
      return false;

    final boolean hasLowerCase = password.chars().anyMatch(c -> Character.isLowerCase(c));
    if (!hasLowerCase)
      return false;

    final boolean hasUpperCase = password.chars().anyMatch(c -> Character.isUpperCase(c));
    if (!hasUpperCase)
      return false;

    final boolean hasDigit = password.chars().anyMatch(c -> Character.isDigit(c));
    if (!hasDigit)
      return false;

    final boolean hasSpecial = password.chars().anyMatch(c -> "!@#$%^&*()-+".indexOf(c) != -1);
    if (!hasSpecial)
      return false;

    for (int i = 1; i < password.length(); ++i)
      if (password.charAt(i) == password.charAt(i - 1))
        return false;
    return true;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def strongPasswordCheckerII(self, password: str) -> bool:
    if len(password) < 8:
      return False
    if not any(c.islower() for c in password):
      return False
    if not any(c.isupper() for c in password):
      return False
    if not any(c.isdigit() for c in password):
      return False
    if not any("!@#$%^&*()-+".find(c) != -1 for c in password):
      return False
    return all(a != b for a, b in zip(password, password[1:]))