码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 32 Longest Valid Parentheses(最长有效括号)(*)

时间:2015-11-26 19:15:52      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

翻译

给定一个仅仅包含“(”或“)”的字符串,找到其中最长有效括号子集的长度。

对于“(()”,它的最长有效括号子集是“()”,长度为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

好久没刷题了,继续努力……

LeetCode 32 Longest Valid Parentheses(最长有效括号)(*)

标签:

原文地址:http://blog.csdn.net/nomasp/article/details/50059357

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!