LeetCode Longest Valid Parentheses

来源:互联网 发布:微小宝mac版 编辑:程序博客网 时间:2024/09/21 08:59

Longest Valid Parentheses

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.

Solution:

class Solution {public:    int longestValidParentheses(string s) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int result=0,curr=0,mymax=0;        for(int i=0;i<s.size();++i){            if(s[i]=='('){                ++curr;            }else{                if(curr>0){                    ++result;                    --curr;                }else{                    s[i]=' ';                    result=0;                    curr=0;                }            }        }        result=0;curr=0;        for(int i=s.size()-1;i>=0;--i){            if(s[i]==' '){                mymax=max(mymax,result);                result=0;                curr=0;                continue;            }            if(s[i]==')'){                ++curr;            }else{                if(curr>0){                    ++result;                    --curr;                }else{                    mymax=max(mymax,result);                    result=0;                    curr=0;                }            }        }        mymax=max(mymax,result);        return mymax*2;    }};