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.
思路
存下标,如果匹配了,先出栈,算i到匹配前的下标的距离,如果此时栈空,i+1。
public class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<>();
int maxLen = 0, n=0;
for(int i=0; i<s.length(); i++){
if(!stack.empty() && s.charAt(stack.peek())=='(' && s.charAt(i)==')'){
stack.pop();
n = stack.empty()? -1:stack.peek();
maxLen = Math.max(maxLen,i-n);
}
else{
stack.push(i);
}
}
return maxLen;
}
}
解法2:动态规划:
d[i]表示以i结尾的最长括号串长度,if s[i]==(,d[i]=0; else { if s[i-d[i-1]-1]==(, d[i]=d[i-1]+2; else d[i]=0 }