https://leetcode.com/problems/longest-valid-parentheses/#/description
Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
For "(()"
, the longest valid parentheses substring is "()"
, which has length = 2.
Another example is ")()())"
, where the longest valid parentheses substring is "()()"
, which has length = 4.
package go.jacob.day707;
import java.util.Stack;
/**
* 32. Longest Valid Parentheses
*
* @author Jacob
*
*/
public class Demo2 {
public int longestValidParentheses(String s) {
if (s == null || s.length() < 1)
return 0;
Stack<Integer> stack = new Stack<Integer>();
int max = 0, left = -1;
for (int i = 0; i < s.length(); i++) {
//如果遍历到左括号,压入堆栈
if (s.charAt(i) == '(')
stack.push(i);
else {
if (!stack.isEmpty()) {
stack.pop();
if (!stack.isEmpty())
max = Math.max(max, i - stack.peek());
else
max = Math.max(max, i - left);
} else
//如果堆栈为空,说明当前的有括号无法配对,需要重新设置left的值
left = i;
}
}
return max;
}
}