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.
You have to consider every possibility, like "(()()", "()((()()", etc
two brilliant O(n) solution
one uses stack, one in DPclass Solution { public: int longestValidParentheses(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function int nMax = 0; const char* p = s.c_str(); const char *str=p; stack<const char*> stk; while (*p ) { if (*p == '(') stk.push(p); else if (*p == ')') { if (!stk.empty() && *stk.top() == '(') { stk.pop();//first pop nMax = max(p - (stk.empty() ? str-1 : stk.top()), nMax);//then count by the last remaining } else stk.push(p); } p++; } return nMax; } };the insight here is to keep the last remaining Parentheses for counting
This DP is definitely not easy to think of. It needs very deep insight.
public class Solution { public int longestValidParentheses(String s) { // Start typing your Java solution below // DO NOT write main() function if(s==null||s.length()==0) return 0; int l=s.length(); int dp[]=new int[l]; int max=0,j; for(int i=1;i<l;i++){ if(s.charAt(i)==')'){ j=i-1-dp[i-1]; if(j>=0&&s.charAt(j)=='(') dp[i]=i-j+1+((j>0)?dp[j-1]:0);} if(dp[i]>max) max=dp[i]; } return max; } }