问题:
给定只包含括号字符'('和 ')''的字符串,请找出最长的有效括号内子括号的长度。举几个例子如下:例如对于"( ()",最长的有效的括号中的子字符串是"()" ,有效双括号数1个,故它的长度为 2。 再比如对于字符串") () () )",其中最长的有效的括号中的子字符串是"() ()",有效双括号数2个,故它的长度为4。 再比如对于"( () () )",它的长度为6。 换言之,便是有效双括号"()"数的两倍。给定函数原型int longestValidParentheses(string s),请完成此函数,实现上述功能。
做法:
利用栈来找到不能和其他半括号配对构成连续有效括号的半括号,把它们作为串的分界,最后遍历各个分界,相邻分界的序号差反映了之间的有效括号个数。复杂度为O(n)。
代码如下:
#include <iostream>
#include <string>
#include <stack>
using namespace std;
struct node{
int order;
int type;
};
class Solution
{
public:
int longestValidParentheses(string s)
{
int max=0, i, length=s.length(), top_order;
stack<node> Q;
struct node tmp;
for(i=0;i<length;i++)
{
if(s[i]=='(')
{
tmp.order = i+1;
tmp.type = 0;
Q.push(tmp);
}
else
{
if(!Q.empty() && Q.top().type==0)
Q.pop();
else
{
tmp.order = i+1;
tmp.type = 1;
Q.push(tmp);
}
}
}
tmp.order = length+1;
tmp.type = 0;
Q.push(tmp);
while(Q.size()>0)
{
top_order = Q.top().order;
Q.pop();
if(!Q.empty())
max = (max>(top_order-Q.top().order-1))? max:(top_order-Q.top().order-1);
else
max = (max>(top_order-1))? max:(top_order-1);
}
return max;
}
};