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

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

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值