A password is considered strong if the below conditions are all met:
1. It has at least 6 characters and at most 20
characters.
2. It contains at least one lowercase letter, at least one uppercase letter, and at least one digit.
3. It does not contain three repeating characters in a row (i.e., "...aaa..."
is weak, but "...aa...a..."
is strong, assuming other conditions are met).
Given a string password, return the minimum number of steps required to make the password strong. if password
is already strong, return 0
.
In one step, you can:
1. Insert one character to password
,
2. Delete one character from password
, or
3. Replace one character of password
with another character.
Example:
Input: password = "aA1"
Output: 3
Approach:
C++
#include <bits/stdc++.h>using namespace std;int strongPasswordChecker(string password){int cnt[3] = {0};// inserstions onlyif (password.size() <= 3){return 6 - password.size();}for (int i = 0; i < password.size(); i++){if (password[i] >= 'a' && password[i] <= 'z')cnt[0] = 1;else if (password[i] >= 'A' && password[i] <= 'Z')cnt[1] = 1;else if (password[i] >= '0' && password[i] <= '9')cnt[2] = 1;}int missing = 3 - (cnt[0] + cnt[1] + cnt[2]);if (password.size() == 4){// one replacement and two insertionsif (missing == 3)return 3;// two insertionselsereturn 2;}else if (password.size() == 5){// two replacement, and one insertionif (missing == 3)return 3;// one replacement, and one insertionelse if (missing == 2)return 2;// one insertion;else if (missing == 1)return 1;// one insertionelsereturn 1;}else if (password.size() >= 6 && password.size() <= 20){int i = 1;int replacements = 0;while (i < password.size()){if (password[i] == password[i - 1]){int j = i - 1;while (i < password.size() && password[i]== password[i - 1])i++;replacements += (i - j) / 3;}else{i++;}}return max(replacements, missing);}else{// password.size() > 20int extra_cnt = password.size() - 20;int i = 1;int replacements = 0;int deleted = 0;vector<int> size_seq;while (i < password.size()){if (password[i] == password[i - 1]){int j = i - 1;while (i < password.size() &&password[i] == password[i - 1])i++;int size = i - j;if ((size % 3) == 0 && extra_cnt){size--;deleted++;extra_cnt--;}if (size >= 3){size_seq.push_back(size);}}else{i++;}}for (int i = 0; i < size_seq.size() &&extra_cnt >= 2; i++){if (size_seq[i] > 3 && (size_seq[i] % 3) == 1){deleted += 2;extra_cnt -= 2;size_seq[i] -= 2;}}for (int i = 0; i < size_seq.size(); i++){while (size_seq[i] >= 3 && extra_cnt >= 3){deleted += 3;extra_cnt -= 3;size_seq[i] -= 3;}replacements += size_seq[i] / 3;}return deleted + extra_cnt + max(replacements, missing);}}int main(){string password = "aA1";cout << strongPasswordChecker(password);return 0;}
No comments:
Post a Comment