Eliminate all valid parentheses, that is, a pair (), and use buyers to save the invalid parentheses in a single (or) subscript in a string. Then the difference between each of the two illegal subscript minus 1 is the length of the legal string in the middle, followed by a backward comparison, to select the largest string.
1 classSolution {2 Public:3 intLongestvalidparentheses (strings) {4stack<int>St;5 intN=s.length (), a,b,longest=0;6 for(intI=0; i<n;i++)7 {8 if(s[i]=='(') St.push (i);9 Else if(!st.empty ())//When the buyers is empty, its top is 0, so determine if it is emptyTen { One if(S[st.top ()]=='(') St.pop (); A ElseSt.push (i); - } - ElseSt.push (i); the - } -A=N; -b=0; + if(St.empty ()) longest=N; - Else + { A while(!st.empty ()) at { -b=st.top (); St.pop (); -Longest=max (longest,a-b-1); -A=b; - } -longest=Max (longest,a); in } - returnlongest; to } +};
The following is a dynamic programming approach:
Each longest represents the most effective length of this segment, which is divided by ') '
1 classSolution {2 Public:3 intLongestvalidparentheses (strings) {4 intn=s.length ();5 intMaxvalid=0;6vector<int> Longest (N,0);7 for(intI=1; i<n;i++)8 {9 if(s[i]==')')Ten { One if(s[i-1]=='(') A { -longest[i]= (I-2) >=0? (longest[i-2]+2):2; -Maxvalid=Max (maxvalid,longest[i]); the } - Else if((i-longest[i-1]-1) >=0&&s[i-longest[i-1]-1]=='('//i-longest[i-1]-1 is to seek this ' (' corresponding ' (' position - { -longest[i]=longest[i-1]+2+ ((i-longest[i-1]-2>=0)? longest[i-longest[i-1]-2]:0); Note that the last curly brace cannot be lost!! +Maxvalid=Max (maxvalid,longest[i]); - } + } A } at returnMaxvalid; - } -};
Longest Valid parentheses