Leetcode 2299. Strong Password Checker II
A password is considered strong if the following criteria are all met:
Given a string password
, return true
if it is a strong password. Otherwise, return false
.
To solve this problem, we can perform the following steps:
true
only if all conditions are satisfied.#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
bool strongPasswordCheckerII(string password) {
if (password.length() < 8) return false;
bool hasLower = false, hasUpper = false, hasDigit = false, hasSpecial = false;
unordered_set<char> specialChars = {'!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+'};
for (int i = 0; i < password.length(); ++i) {
char c = password[i];
if (i > 0 && password[i] == password[i - 1]) return false; // No two adjacent characters should be the same
if (islower(c)) hasLower = true;
if (isupper(c)) hasUpper = true;
if (isdigit(c)) hasDigit = true;
if (specialChars.find(c) != specialChars.end()) hasSpecial = true;
}
return hasLower && hasUpper && hasDigit && hasSpecial;
}
// Example usage:
int main() {
string password = "Aa1!Aa1!";
if (strongPasswordCheckerII(password)) {
cout << "Password is strong." << endl;
} else {
cout << "Password is not strong." << endl;
}
return 0;
}
The time complexity of this solution is O(n), where n is the length of the password. This is because we iterate through each character in the password exactly once to check all the conditions.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?