题目
考虑一种简单的正则表达式:
只由 x ( ) | 组成的正则表达式。
小明想求出这个正则表达式能接受的最长字符串的长度。
例如 ((xx|xxx)x|(x|xx))xx 能接受的最长字符串是: xxxxxx,长度是6。
输入
----
一个由x()|组成的正则表达式。输入长度不超过100,保证合法。
输出
----
这个正则表达式能接受的最长字符串的长度。
例如,
输入:
((xx|xxx)x|(x|xx))xx
程序应该输出:
6
思路 括号表示优先计算,| 表示的是或
代码
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
using namespace std;
char s[1000];
int i=0;
int f()
{
int maxn=0;
int temp=0;
while(i<strlen(s)){
if(s[i]=='('){
i++;
temp+=f();// 统计一对括号中X的最大值返回之后将它记录到当前括号中
}
else if(s[i]==')'){
i++;
break;
}
else if(s[i]=='|'){
i++;
if(temp>maxn) maxn=temp; // 统计遇到|时候x的最大值保存到maxn
temp=0; // 从新计数
}
else{
temp++;
i++;
}
}
if(temp>maxn) maxn=temp; // 每一次遇到右括号比较|之间的最大值将它保存在maxn
return maxn;
}
int main()
{ scanf("%s",s);
cout<<f()<<endl;
return 0;
}