LeetCode420. Strong Password Checker

齐冥夜
2023-12-01

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

 

 类似资料:

相关阅读

相关文章

相关问答