翻译
给定一个仅仅包含“(”或“)”的字符串,找到其中最长有效括号子集的长度。
对于“(()”,它的最长有效括号子集是“()”,长度为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
好久没刷题了,继续努力……