|
| 1 | +/** |
| 2 | + * 420. Strong Password Checker |
| 3 | + * https://leetcode.com/problems/strong-password-checker/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * A password is considered strong if the below conditions are all met: |
| 7 | + * - It has at least 6 characters and at most 20 characters. |
| 8 | + * - It contains at least one lowercase letter, at least one uppercase letter, and at |
| 9 | + * least one digit. |
| 10 | + * - It does not contain three repeating characters in a row (i.e., "Baaabb0" is weak, |
| 11 | + * but "Baaba0" is strong). |
| 12 | + * |
| 13 | + * Given a string password, return the minimum number of steps required to make password |
| 14 | + * strong. if password is already strong, return 0. |
| 15 | + * |
| 16 | + * In one step, you can: |
| 17 | + * - Insert one character to password, |
| 18 | + * - Delete one character from password, or |
| 19 | + * - Replace one character of password with another character. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {string} password |
| 24 | + * @return {number} |
| 25 | + */ |
| 26 | +var strongPasswordChecker = function(password) { |
| 27 | + const types = 3 - (/[a-z]/.test(password) + /[A-Z]/.test(password) + /[0-9]/.test(password)); |
| 28 | + let replacements = 0; |
| 29 | + let modOneCount = 0; |
| 30 | + let modTwoCount = 0; |
| 31 | + |
| 32 | + if (password.length < 6) { |
| 33 | + return Math.max(6 - password.length, types); |
| 34 | + } |
| 35 | + |
| 36 | + for (let i = 0; i < password.length;) { |
| 37 | + let j = i; |
| 38 | + while (j < password.length && password[j] === password[i]) { |
| 39 | + j++; |
| 40 | + } |
| 41 | + const repeatLength = j - i; |
| 42 | + if (repeatLength >= 3) { |
| 43 | + replacements += Math.floor(repeatLength / 3); |
| 44 | + if (repeatLength % 3 === 0) modOneCount++; |
| 45 | + if (repeatLength % 3 === 1) modTwoCount++; |
| 46 | + } |
| 47 | + i = j; |
| 48 | + } |
| 49 | + |
| 50 | + if (password.length <= 20) { |
| 51 | + return Math.max(types, replacements); |
| 52 | + } |
| 53 | + |
| 54 | + const deletions = password.length - 20; |
| 55 | + replacements -= Math.min(deletions, modOneCount); |
| 56 | + replacements -= Math.min(Math.max(deletions - modOneCount, 0), modTwoCount * 2) / 2; |
| 57 | + replacements -= Math.max(deletions - modOneCount - modTwoCount * 2, 0) / 3; |
| 58 | + |
| 59 | + return deletions + Math.max(types, Math.max(0, Math.ceil(replacements))); |
| 60 | +}; |
0 commit comments