
Given a string containing ‘(‘ and ‘)’, find the length of 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;
int longestValidParentheses(string s){ int maxLength = 0; stack<char>st; stack<int>pos; for(int i=0; i<s.size(); i++){ if(s[i] == '('){ st.push(s[i]); pos.push(i); } else{ if(!st.empty() && st.top() == '('){ st.pop(); pos.pop(); int p = st.empty() ? -1 : pos.top(); maxLength = max(maxLength, i-p); } else{ st.push(s[i]); pos.push(i); } } } return maxLength;}




近期评论