题解 | #有效括号序列#

有效括号序列

http://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2

数组索引版本

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 
 * @param s string字符串 
 * @return bool布尔型
 */
export function isValid(s: string): boolean {
    // write code here
    // 要求:空间复杂度 O(n),时间复杂度 O(n)
    const tpl = ['[',']','{','}','(',')']
    const len = s.length
        
    // 奇数长度肯定不闭合
    if(len % 2){return false}
    // 第一个是不能是偶数
    if((tpl.indexOf(s[0]) + 1) % 2 === 0){
        return false
    }
    
    // 左边栈,先把第一个入栈
    const leftArr: string[] = [s[0]]
    
    // 从第二个开始
    for(let i = 1; i < len; i++){
        const tplIdx = tpl.indexOf(s[i])
        if(tplIdx < 0){
           return false
        }
        // 奇数, 左边
        if((tplIdx + 1) % 2){
            // 把自己推入栈
            leftArr.push(tpl[tplIdx])
        }else{
            // 遇到右边,需要出栈判断是不是匹配另一半, 不匹配的直接验证失败
            if(tpl[tplIdx - 1] !== leftArr.pop()){
              return false
            }
        }

    }
    
    
    return !leftArr.length
}
全部评论

相关推荐

05-12 16:04
已编辑
江西财经大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务