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
}
相关推荐
让我们一起加油好吗2 天前
【算法刷题】LeetCode 力扣 Hot 100 刷题记录
数据结构·c++·算法·leetcode·面试·笔试
Rain的Java大神之路2 天前
LeetCode 42「接雨水」:面试官百出不厌的题,一文讲透从暴力到双指针 O(1)
java·后端·leetcode
codeejun3 天前
每日一Go·MySQL-22、幻读、不可重复读、脏读实战演示
开发语言·mysql·golang
码途行者3 天前
每天10分钟学Go:第17课 接口interface-只规定“能做什么“,不管它是什么
开发语言·后端·golang
利威尔xu3 天前
2026-11-24-Go限流器实战
后端·golang
Navigator_Z4 天前
LeetCode //C - 1320. Minimum Distance to Type a Word Using Two Fingers
c语言·算法·leetcode
码途行者4 天前
每天10分钟学Go:第21课 错误
开发语言·后端·golang
码途行者4 天前
每天10分钟学Go:第22课 自定义错误
开发语言·后端·golang
wy_hhxx4 天前
[Leetcode] 滑动窗口
算法·leetcode·滑动窗口
码途行者4 天前
每天10分钟学Go:第20课 泛型
c++·算法·golang