题目大意:
给定一个括号字符串,求出这个括号字符串中最长合法的字符串长度=及个数;
思路分析:
①:当前字符是‘(’,入栈;
②:当前字符是 ' ) ',如果栈是空的或者栈顶元素是’)‘,入栈;否则,栈顶元素出栈,并让新的栈顶元素的num加上出栈元素的num(num代表合法子串的长度)并再加上2(合法子串长度加2),要注意特别判断栈为空的情况,我是用了一个ans变量来代表空了的栈的栈顶元素,再比较最长的合法子串的长度及个数。
代码实现:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<stack>
#define Max(a,b) ((a)>(b)?(a):(b))
using namespace std;
const int N=1000010;
char st[N];
struct Node{
int num,flag;
Node(int _num=0,int _flag=0):num(_num),flag(_flag){}
};
stack<Node> s;
int main(){
while(~scanf("%s",st)){
while(!s.empty()) s.pop();
int l=strlen(st);
int ans=0,tmp,max_l=0,num=0;
for(int i=0;i<l;++i){
if(st[i]=='(') s.push(Node(0,0));
else if(st[i]==')'){
if(s.empty()||s.top().flag==1){
s.push(Node(0,1));
continue;
}
if(!s.empty()){
tmp=s.top().num;
s.pop();
if(!s.empty()){
s.top().num+=tmp+2;
if(max_l==s.top().num) num++;
else if(max_l<s.top().num) max_l=s.top().num,num=1;
}
else{
ans+=tmp+2;
if(max_l==ans) num++;
else if(max_l<ans) max_l=ans,num=1;
}
}
}
}
if(max_l==0) printf("0 1\n");
else printf("%d %d\n",max_l,num);
}
}