Leetcode 32. 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.

分析

寻找一个子串,包含最长的有效圆括号对。可以通过栈来统计一共出现了多少对圆括号。但是要找最长子字符串,就需要进一步分析。
一个子函数用来判断后续的前缀字符串是否圆括号匹配,如果匹配就可以与前面的子串相加,否则就是新的子串,重新判断最大长度。

int validSubstring(char *s,int length)
{
    int left=0;
    while(s[length]!='\0')
    {
        if(s[length]==')')
        {
            if(left<=0)return -1;
            else if(left==1) 
                return 1;
            else
                left--;
        }
        else
        {
            left++;
        }
        length++;
    }
    if(left>0)return -1;
    else return 1;
}
int longestValidParentheses(char* s) {
    int ans=0,temp=0,length=0,left=0,lastleft=0;
    while(s[length]!='\0')
    {
        if(s[length]=='(')
        {
            if(validSubstring(s,length)==-1)
            {
                temp=0;
                left=1;
            }
            else
                left++;
        }
        else
        {
            if(left>0)
            {
                left--;
                temp++;
                if(temp>ans)ans=temp;
            }
            else
            {
                left=0;
                temp=0;
            }
        }
        //printf("%d %d\n",left,temp);
        length++;
    }
    return ans*2;
}

你可能感兴趣的:(Leetcode 32. Longest Valid Parentheses)