1 题目
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.
2 解法
public class Solution {
public int longestValidParentheses(String s) {
int size = s.length();
Stack<Integer> stack = new Stack<Integer>();
stack.push(-1);
int result = 0;
for(int i = 0; i < size; i++){
if(s.charAt(i) == ')' && stack.size() > 1 && s.charAt(stack.peek()) == '('){
stack.pop();
result = Math.max(result, i - stack.peek());
}else{
stack.push(i);
}
}
return result;
}
}