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.
Subscribe to see which companies asked this question
Hide Similar Problems
class Solution { public: int longestValidParentheses(string s) { int sSize = s.size(); int maxLen = 0; int start = -1,end = 0; vector<int> matches(sSize,-1);//每个字符的匹配情况,字符为'('是值为-1,字符为')'时,值为其匹配的左括号的位置 stack<int> stk;//左括号的位置 for(int i=0;i<sSize;i++){ if(s[i]=='('){ stk.push(i); continue; } if(!stk.empty()){ start = stk.top(); end = i+1; matches[i] = start;//与i这个位置发生匹配的字符的位置是node.index while(start>0 && matches[start-1]!=-1){ start = matches[start-1]; } maxLen = max(maxLen,end-start); stk.pop(); } } return maxLen; } }; /** (()(())) */