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.
//()(()()() 难点在于这种res6 ()(()()())这种10
class Solution {
public:
int longestValidParentheses(string s)
{
stack<int> Num;
int n=0, res = 0,start=0;;
if (s.empty())
return 0;
for(;n<s.size();++n)
{
if (s[n] == '(')
{
Num.push(n);
}
else
{
if (!Num.empty())
{
//int tmp = Num.top();
Num.pop();
//res = Num.empty()?max(res,n-start+1):max(res,n-tmp+1);
res = Num.empty()?max(res,n-start+1):max(res,n-Num.top());//这里一定是这样子 (()() 上一行结果是2
}
else
start = n+1;
}
}
return res;
}
};
测试
#include<algorithm>
#include<iostream>
#include<string>
#include<stack>
using namespace std;
class Solution {
public:
int longestValidParentheses(string s)
{
stack<int> Num;
int n=0, res = 0,start=0;;
if (s.empty())
return 0;
for(;n<s.size();++n)
{
if (s[n] == '(')
{
Num.push(n);
}
else
{
if (!Num.empty())
{
Num.pop();
res = Num.empty()?max(res,n-start+1):max(res,n-Num.top());
}
else
start = n+1;
}
}
return res;
}
};
int main ()
{
Solution s;
string ss("()(()()()");
cout<<"res"<<s.longestValidParentheses(ss)<<endl;
}