天天看点

leetcode刷题笔记(Golang)--32. Longest Valid Parentheses

32. Longest Valid Parentheses

Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.

Example 1:

Input: “(()”

Output: 2

Explanation: The longest valid parentheses substring is “()”

Example 2:

Input: “)()())”

Output: 4

Explanation: The longest valid parentheses substring is “()()”

func longestValidParentheses(s string) int {
	stack := []int{}
	res := 0
	begin := 0
	for i, v := range s {
		if v == '(' {
			stack = append(stack, i)
		} else {
			if len(stack) == 0 {
				begin = i + 1
			} else {
				lg := len(stack)
				stack = stack[:lg-1]
				cur := i - begin + 1
				if len(stack) > 0 {
					cur = i - stack[len(stack)-1]
				}
				if res < cur {
					res = cur
				}
			}
		}
	}
	return res
}