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.
class Solution { public: int longestValidParentheses(string s) { // Note: The Solution object is instantiated only once and is reused by each test case. stack<int> left; int max=0; vector<bool> vec; vec.resize(s.length(),false); for(int i=0;i<s.length();i++){ if(s[i]=='(')left.push(i); else if(s[i]==')'){ if(left.size()!=0) { vec[left.top()]=true; left.pop(); vec[i]=true; } } } int count=0; for(int i=0;i<s.length();i++){ if(vec[i]){ count++; if(count>max)max=count; } else count=0; } return max; } };