1. 程式人生 > >LeetCode 32 Longest Valid Parentheses(最長有效括號)(*)

LeetCode 32 Longest Valid Parentheses(最長有效括號)(*)

翻譯

給定一個僅僅包含“(”或“)”的字串,找到其中最長有效括號子集的長度。

對於“(()”,它的最長有效括號子集是“()”,長度為2。

另一個例子“)()())”,它的最長有效括號子集是“()()”,其長度是4。

原文

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) {
    stack<char> brackets;
    int length = 0;
    int index = 0;
    while
(index < s.size()) { if(brackets.empty()) { brackets.push(s[index]); ++ index; } else { if(brackets.top() == '(' && s[index] == ')') { length += 2; ++ index; brackets.pop(); } else
{ brackets.push(s[index]); ++ index; } } } return length; } };

結果發現我理解錯了題意,比如說“()(()”這種,其長度應該是2為不是4,因為必須是連續的。我的思路又轉換不過來了,就一直糾結……

我嘗試把加“2”這個操作寫在字串中,然後對於括號的不連續在該字串中用空格(” “)來打”斷點“,最後對字串進行解析。

然而最終還是沒能寫出來……又去求助了……

class Solution {
public:
int longestValidParentheses(string s) {
    stack<int> brackets;
    brackets.push(0);
    int res = 0;
    for(int i = 0; i < s.length(); ++ i) {
        if(s[i] == '(') {
            brackets.push(i + 1);
        } else {
            brackets.pop();
            if(brackets.size()) {
                res = max(res, i + 1 - brackets.top());
                cout<<brackets.top()<<endl;;
            } else {
                brackets.push(i + 1);
            }
        }
    }
    return res;
}
};
 (  )  (  (  )
  0  1   2   3  4

i = 0   0,1
i = 1   0      top = 0    res = 2
i = 2   0,3    
i = 3   0,3,4
i = 4   0,3    top = 3    res = 2

好久沒刷題了,繼續努力……