参考宫水三叶题解,非常有启发意义https://leetcode.cn/problems/valid-parenthesis-string/solutions/992601/gong-shui-san-xie-yi-ti-shuang-jie-dong-801rq/
- 最长有效括号
使用栈+一次遍历,巧妙得出最长有效括号长度
func longestValidParentheses(s string) int {
stack := make([]int,0)
stack =append(stack,-1)
mx := 0
for i:=0;i<len(s);i++{
if s[i]=='('{
stack = append(stack,i)
}else{
stack = stack[:len(stack)-1]
if len(stack) == 0 {
stack =append(stack,i)
}else{
mx =max(mx,i-stack[len(stack)-1])
}
}
}
return mx
}