Golang | Leetcode Golang题解之第32题最长有效括号

题目:

题解:

Go 复制代码
func longestValidParentheses(s string) int {
    left, right, maxLength := 0, 0, 0
    for i := 0; i < len(s); i++ {
        if s[i] == '(' {
            left++
        } else {
            right++
        }
        if left == right {
            maxLength = max(maxLength, 2 * right)
        } else if right > left {
            left, right = 0, 0
        }
    }
    left, right = 0, 0
    for i := len(s) - 1; i >= 0; i-- {
        if s[i] == '(' {
            left++
        } else {
            right++
        }
        if left == right {
            maxLength = max(maxLength, 2 * left)
        } else if left > right {
            left, right = 0, 0
        }
    }
    return maxLength
}

func max(x, y int) int {
    if x > y {
        return x
    }
    return y
}
相关推荐
铁皮哥14 小时前
【力扣题解】LeetCode 25. K 个一组翻转链表
java·数据结构·windows·python·算法·leetcode·链表
洛水水15 小时前
【力扣100题】29. 对称二叉树
算法·leetcode·职场和发展
洛水水15 小时前
【力扣100题】26. 二叉树的中序遍历
算法·leetcode·深度优先
sheeta199815 小时前
LeetCode 每日一题笔记 日期:2026.05.11 题目:2553. 分割数组中数字的数位
笔记·算法·leetcode
码农阿豪16 小时前
Go 语言操作金仓数据库(上篇):环境搭建与连接管理
开发语言·数据库·golang
我爱cope16 小时前
【滑动窗口:力扣438找到字符串中所有字母异位词】
算法·leetcode·职场和发展
码农阿豪16 小时前
Go 语言操作金仓数据库(下篇):SQL 执行、类型映射与超时控制
数据库·sql·golang
洛水水16 小时前
【力扣100题】27. 二叉树的最大深度
算法·leetcode·图论
_深海凉_16 小时前
LeetCode热题100-删除链表的倒数第 N 个结点
算法·leetcode·链表
小雅痞16 小时前
[Java][Leetcode middle] 73. 矩阵置零
java·leetcode·矩阵