考虑一种简单的正则表达式:
只由 x ( ) | 组成的正则表达式。
小明想求出这个正则表达式能接受的最长字符串的长度。
例如 ((xx|xxx)x|(x|xx))xx 能接受的最长字符串是: xxxxxx,长度是6。
输入
一个由x()|组成的正则表达式。输入长度不超过100,保证合法。
输出
这个正则表达式能接受的最长字符串的长度。
例如,
输入:
((xx|xxx)x|(x|xx))xx
程序应该输出:
6
扫描,对不同的情况分别处理
#include<iostream>
using namespace std;
char a[101];
int count=-1;
int f()
{
int x=0;//还在动态生成的那部分
int y=0;//当前已经确定的那部分
while(1)
{
count++;
if(a[count]=='x')
{
x+=1;
}
else if(a[count]=='(')
{
x+=f();
}
else if(a[count]=='|')
{
y=((x>=y)? x:y);
x=0;//x需要归零!!!
}
else
{
y=((x>=y)? x:y);
return y;
}
}
}
int main()
{
cin>>a;
cout<<f();
}