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

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

目录
相关文章
|
1月前
|
存储 C语言 索引
环形链表、环形链表 II、有效的括号​​​​​​​【LeetCode刷题日志】
环形链表、环形链表 II、有效的括号​​​​​​​【LeetCode刷题日志】
|
3月前
leetcode-301:删除无效的括号
leetcode-301:删除无效的括号
19 0
|
3月前
|
Java C++ Python
leetcode-20:有效的括号
leetcode-20:有效的括号
30 0
|
4月前
|
测试技术
LeetCode | 20.有效的括号(C语言版)
LeetCode | 20.有效的括号(C语言版)
39 0
LeetCode | 20. 有效的括号
LeetCode | 20. 有效的括号
|
3月前
|
Go
golang力扣leetcode 301.删除无效的括号
golang力扣leetcode 301.删除无效的括号
33 0
|
1月前
|
算法 安全 Java
【数据结构与算法】6、栈(Stack)的实现、LeetCode:有效的括号
【数据结构与算法】6、栈(Stack)的实现、LeetCode:有效的括号
21 0
|
2月前
|
Java
|
2月前
LeetCode题 338比特位计数,20有效的括号,415字符串相加
LeetCode题 338比特位计数,20有效的括号,415字符串相加
35 0
|
3月前
leetcode:20. 有效的括号
leetcode:20. 有效的括号
12 0

热门文章

最新文章