一.问题描述
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.
二.我的解题思路
拿到这个题目,我的思路比较naive。就是在每个(位置都要去找所能匹配的最长子串,但是这样做的时间复杂度比较高。之后参考了网上的资料,转变思路。针对括号匹配这一问题的特殊性,可以尝试去遍历一次字符串,记录下匹配的子串的长度,再取最大值。参考博客http://blog.youkuaiyun.com/zhangwei1120112119/article/details/16812679
程序如下:
class Solution
{
public:
int longestValidParentheses(string s)
{
stack<int>S;
S.push(-1);
int ans=0;
for(string::size_type i=0;i<s.size();i++)
{
//printf("%d\n",S.size());
char ch=s[i];
if(ch == '(')
{
S.push(i);
}
else
{
if(S.size()>1)
{
S.pop();
int tmp=S.top();
ans=max(ans,(int)i-tmp);
}
else
{
S.pop();
S.push(i);
}
}
}
return ans;
}
};