Created
March 18, 2025 12:14
-
-
Save shricodev/da1aaf844b36f7009104dcd21335b4c2 to your computer and use it in GitHub Desktop.
Test Case Pass: 51/54
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution { | |
| public: | |
| int strongPasswordChecker(string password) { | |
| int n = password.size(); | |
| // Check for missing character types | |
| bool has_lower = false, has_upper = false, has_digit = false; | |
| for (char c : password) { | |
| if (islower(c)) has_lower = true; | |
| else if (isupper(c)) has_upper = true; | |
| else if (isdigit(c)) has_digit = true; | |
| } | |
| int missing = 3 - (has_lower + has_upper + has_digit); | |
| // Check for repeating sequences and calculate initial required_repeats | |
| vector<int> repeat_counts; | |
| int required_repeats = 0; | |
| int i = 0; | |
| while (i < n) { | |
| int j = i; | |
| while (j < n && password[j] == password[i]) ++j; | |
| int len = j - i; | |
| if (len >= 3) { | |
| repeat_counts.push_back(len); | |
| required_repeats += len / 3; | |
| } | |
| i = j; | |
| } | |
| if (n < 6) { | |
| return max(6 - n, missing + required_repeats); | |
| } else if (n <= 20) { | |
| return max(missing, required_repeats); | |
| } else { // n > 20 | |
| int over = n - 20; | |
| int delete_ops = over; | |
| // Categorize repeats by their mod 3 value | |
| int r0 = 0, r1 = 0, r2 = 0; | |
| for (int l : repeat_counts) { | |
| int mod = l % 3; | |
| if (mod == 0) r0++; | |
| else if (mod == 1) r1++; | |
| else r2++; | |
| } | |
| // Apply deletions to reduce required_repeats optimally | |
| int use; | |
| use = min(r0, over); | |
| required_repeats -= use; | |
| over -= use; | |
| use = min(r1, over / 2); | |
| required_repeats -= use; | |
| over -= use * 2; | |
| use = over / 3; | |
| required_repeats -= use; | |
| over -= use * 3; | |
| required_repeats = max(required_repeats, 0); | |
| return delete_ops + max(missing, required_repeats); | |
| } | |
| } | |
| }; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Problem Link: https://leetcode.com/problems/strong-password-checker