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
struct Char{ char c; int index; Char(char c,int index):c(c),index(index){} }; class Solution { public: int longestValidParentheses(string s) { int sSize = s.size(); if(sSize <=1){ return 0; } int maxLen = 0; vector<int> matches(sSize,-1); stack<Char> stk; if(s[0]==‘(‘){ stk.push(Char(s[0],0)); } int start = -1,end = 0; for(int i=1;i<sSize;i++){ // cout<<"i="<<i<<",stk.empty()="<<stk.size()<<endl; if(stk.empty()){//栈空的分支 if(s[i]==‘(‘){ stk.push(Char(s[i],i)); } continue; } //栈不空的分支 Char node = stk.top(); if(node.c==s[i]){//不匹配 stk.push(Char(s[i],i)); continue; } stk.pop(); matches[i] = node.index;//与i这个位置发生匹配的字符的位置是node.index end = i+1; start = matches[i]; while(start>0 && matches[start-1]!=-1){ start = matches[start-1]; } maxLen = max(maxLen,end-start); } return maxLen; } }; /** (()(()))
"((()))())"
*/
[string]Longest Valid Parentheses
原文:http://www.cnblogs.com/zengzy/p/5027241.html