My just so so js solution


  • 0
    B
    /**
     * @param {string} s
     * @return {number}
     */
    function strongPasswordChecker(s) {
        if (s.length <= 4) return 6 - s.length
        let dontContainsDigit = !s.match(/\d/)
        let dontContainsLower = !s.match(/[a-z]/)
        let dontContainsUpper = !s.match(/[A-Z]/)
        let needReplaceNum = dontContainsDigit + dontContainsLower + dontContainsUpper
        if (s.length === 5) return Math.max(1, needReplaceNum)
        
        let needDeleteNum = s.length > 20 ? s.length - 20 : 0
        let lens = []
        for (let i = 0, j; i < s.length; i = j) {
            for (j = i + 1; j < s.length && s[j] === s[i]; j++)
                ;
            let len = j - i
            if (len > 2) lens.push(j - i)
        }
        
        let num = needDeleteNum
        for (let [remain, toDelete] of [[0, 1], [1, 2], [2, 3]]) {
            if (needDeleteNum) {
                let tmpLens = []
                for (let len of lens) {
                    if (len % 3 === remain && needDeleteNum) {
                        let delta = Math.min(toDelete, needDeleteNum)
                        needDeleteNum -= delta
                        len -= delta
                    }
                    if (len > 2) tmpLens.push(len)
                }
                lens = tmpLens
            }
        }
        num += needReplaceNum
        for (let len of lens) {
            let shouldAdd = Math.floor(len / 3)
            if (needReplaceNum) {
                let discount = Math.min(shouldAdd, needReplaceNum)
                shouldAdd -= discount
                needReplaceNum -= discount
            }
            num += shouldAdd
        }
        
        return num
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.