首页 > 其他 > 详细

[string]Longest Valid Parentheses

时间:2015-12-07 20:50:38      阅读:152      评论:0      收藏:0      [点我收藏+]

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

Show Tags
Hide Similar Problems
 (E) Valid Parentheses
 
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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!