阅读 128

LeetCode第22天🐱‍🏍

678. 有效的括号字符串

  • 贪心

设置minCountmaxCount两个计数器

遍历字符串s,维护maxCount的值,当maxCount<0时,即当前位置之前的')'数量大于'(''*'的数量之和,返回false

minCount表示未匹配的'('minCount应为非负整数,当minCount===0时返回true

var checkValidString = function(s) {
    let minCount = 0, maxCount = 0
    for (let str of s) {
        if (str === '(') {
            minCount++
            maxCount++
        }
        else if (str === ')') {
            minCount = Math.max(--minCount, 0)
            maxCount--
            if (maxCount  < 0) return false
        }
        else {
            minCount = Math.max(--minCount, 0)
            maxCount++
        }
    }
    return minCount === 0
}
复制代码

利用栈先进后出的特性,在栈内存储元素下标

var checkValidString = function(s) {
    const leftStack = []
    const asteriskStack = []
    const n = s.length
    for (let i = 0; i < n; i++) {
        const c = s[i]
        if (c === '(') {
            leftStack.push(i)
        }
        if (c === '*') {
            asteriskStack.push(i)
        }
        else {
            if (leftStack.length) {
                leftStack.pop()
            } else if (asteriskStack.length) {
                asteriskStack.pop()
            } else 
                return false
        }
    }
    while (leftStack.length && asteriskStack.length) {
        const leftIndex = leftStack.pop();
        const asteriskIndex = asteriskStack.pop();
        if (leftIndex > asteriskIndex) {
            return false;
        }
    }
    return leftStack.length === 0;
}
复制代码
文章分类
前端