LeetCode420. Strong Password Checker

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 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);
		}
	}
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值