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;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容