A password is considered strong if below conditions are all met:

1. It has at least 6 characters and at most 20 characters.
2. It must contain at least one lowercase letter, at least one uppercase letter, and at least one digit.
3. It must NOT contain three repeating characters in a row ("...aaa..." is weak, but "...aa...a..." is strong, assuming other conditions are met).

Write a function strongPasswordChecker(s), that takes a string s as input, and return the MINIMUM change 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.

1. 长度问题，当长度小于6的时候，我们要通过插入字符来补充长度，当长度超过20时，我们要删除字符。

2. 缺失字符或数字，当我们缺少大写，小写和数字的时候，我们可以通过插入字符或者替换字符的方式来补全。

3. 重复字符，这个也是本题最大的难点，因为插入，删除，或者置换都可以解决重复字符的问题，比如有一个字符串"aaaaa"，我们可以用一次置换，比如换掉中间的字符'a'；或者两次插入字符，在第二个a和第四个a后面分别插入一个非a字符；或者可以删除3个a来解决重复字符的问题。由于题目要求我们要用最少的步骤，那么显而易见置换是最高效的去重复字符的方法。

class Solution {
public:
int res = 0, n = s.size(), lower = 1, upper = 1, digit = 1;
vector<int> v(n, 0);
for (int i = 0; i < n;) {
if (s[i] >= 'a' && s[i] <= 'z') lower = 0;
if (s[i] >= 'A' && s[i] <= 'Z') upper = 0;
if (s[i] >= '0' && s[i] <= '9') digit = 0;
int j = i;
while (i < n && s[i] == s[j]) ++i;
v[j] = i - j;
}
int missing = (lower + upper + digit);
if (n < 6) {
int diff = 6 - n;
res += diff + max(0, missing - diff);
} else {
int over = max(n - 20, 0), left = 0;
res += over;
for (int k = 1; k < 3; ++k) {
for (int i = 0; i < n && over > 0; ++i) {
if (v[i] < 3 || v[i] % 3 != (k - 1)) continue;
v[i] -= k;
over -=k;
}
}
for (int i = 0; i < n; ++i) {
if (v[i] >= 3 && over > 0) {
int need = v[i] - 2;
v[i] -= over;
over -= need;
}
if (v[i] >= 3) left += v[i] / 3;
}
res += max(missing, left);
}
return res;
}
};

https://discuss.leetcode.com/topic/63854/o-n-java-solution-by-analyzing-changes-allowed-to-fix-each-condition/2

LeetCode All in One 题目讲解汇总(持续更新中...)

 微信打赏 Venmo 打赏
posted @ 2016-10-22 23:54  Grandyang  阅读(8961)  评论(5编辑  收藏  举报