A password is considered strong if below conditions are all met:
Write a function strongPasswordChecker(s), that takes a string s as input, and return the MINIMUMchange required to make s a strong password. If s is already strong, return 0.
Insertion, deletion or replace of any one character are all considered as one change.
参考资料:here。
class Solution {
public:
int strongPasswordChecker(string s) {
int needUpper = 1, needLower = 1, needDigit = 1;
vector<int> repeat;
int count = 1, n = s.size(), needs = 0, chRepeat = 0;
if (n == 0) return 6;
for (int i = 0; i < n; i++) {
if (isupper(s[i])) needUpper = 0;
if (islower(s[i])) needLower = 0;
if (isdigit(s[i])) needDigit = 0;
if (i == 0) continue;
if (s[i] == s[i - 1]) count++;
else {
if (count >= 3) {
chRepeat += count / 3;
repeat.push_back(count);
}
count = 1;
}
}
if (count >= 3) {
chRepeat += count / 3;
repeat.push_back(count);
}
needs = needUpper + needLower + needDigit;
if (n < 6) return max(6 - n, max(chRepeat, needs));
else if (n <= 20) return max(needs, chRepeat);
else {
int r = n - 20;
chRepeat = 0;
auto cmp = [](int a, int b) {return (a % 3) < (b % 3); };
sort(repeat.begin(), repeat.end(), cmp);
for (int i = 0; i < repeat.size(); i++) {
if (repeat[i] % 3 == 2) break;
int tmp = (repeat[i] % 3) + 1;
if (r >= tmp) {
repeat[i] -= tmp;
r -= tmp;
}
else {
repeat[i] -= r;
r = 0;
break;
}
}
for (int i = 0; i < repeat.size(); i++) {
int tmp = ((repeat[i] - 2) / 3) * 3;
if (r!= 0 && r >= tmp) {
r -= tmp;
}
else {
chRepeat += (repeat[i] - r) / 3;
r=0;
}
}
return n - 20 + max(needs, chRepeat);
}
}
};