32. Longest Valid Parentheses

Description:

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.


簡要題解:

從左到右開始統計,無論何時左括號的數量一定都大於或等於右括號的數量。

類似地,從右到左開始統計,無論何時右括號的數量一定都大於或等於左括號的數量。

可以先從左邊開始順序地向右移動,計算出所有有效括號子串的長度,不斷更新“當前最大長度”。

由於缺乏對稱性,所以想要遍歷所有情況必須再從右往左計算一遍。原理類似。最後得出的“當前最大長度”就是所要求的最大長度。


代碼:

class Solution {
public:
    int longestValidParentheses(string s) {
        int maxLength = 0, l = 0, r = 0;

        for (int i = 0; i < s.size(); i++) {
            if (s[i] == '(')
                l++;
            else
                r++;

            if (l == r)
                maxLength = (l + r > maxLength) ? l + r : maxLength;

            if (l < r)
                l = r = 0;
        }
        
        l = r = 0;
        for (int i = s.size() - 1; i >= 0; i--) {
            if (s[i] == '(')
                l++;
            else
                r++;

            if (l == r)
                maxLength = (l + r > maxLength) ? l + r : maxLength;

            if (l > r)
                l = r = 0;
        }

        return maxLength;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章