个人思路总结:
这个题和Leetcode-20差不多,只不过那个题只需要判断有多少个有效括号。而此题需要判断有多少个连续有效括号。至于判断是否为有效括号的方法与20题类似,借助栈stack即可实现。判断最长连续子串的方法和Leetcode-3比较类似。
代码如下:
class Solution {
public:
int longestValidParentheses(string s) {
int len = s.size();
stack<int> tmp;
int count = 0;
int start = 0;
for(int i=0;i<len;i++)
{
if(s[i]=='(')
//注意这里是将index放进stack,这是和20题的区别
tmp.push(i);
else
{
if(tmp.empty())
//确定最长连续有效括号的起始位置
start = i+1;
else
{
if(s[i]==')')
{
tmp.pop();
//这里需要判断栈是否为空,举个例子"(()"
count = tmp.empty() ? max(count, i - start + 1) :max(count, i - tmp.top());
}
}
}
}
return count;
}
};