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
}
相关推荐
大二转专业5 小时前
408算法题leetcode--第24天
考研·算法·leetcode
__AtYou__11 小时前
Golang | Leetcode Golang题解之第448题找到所有数组中消失的数字
leetcode·golang·题解
转调12 小时前
每日一练:地下城游戏
开发语言·c++·算法·leetcode
千年死缓13 小时前
go+redis基于tcp实现聊天室
redis·tcp/ip·golang
huanxiangcoco13 小时前
152. 乘积最大子数组
python·leetcode
希望有朝一日能如愿以偿15 小时前
力扣题解(飞机座位分配概率)
算法·leetcode·职场和发展
Espresso Macchiato15 小时前
Leetcode 3306. Count of Substrings Containing Every Vowel and K Consonants II
leetcode·滑动窗口·leetcode medium·leetcode 3306·leetcode周赛417
数据分析螺丝钉16 小时前
力扣第240题“搜索二维矩阵 II”
经验分享·python·算法·leetcode·面试
￴ㅤ￴￴ㅤ9527超级帅16 小时前
LeetCode hot100---数组及矩阵专题(C++语言)
c++·leetcode·矩阵
吃着火锅x唱着歌17 小时前
Redis设计与实现 学习笔记 第五章 跳跃表
golang