您的位置:首页 > 其它

2017蓝桥杯A组(正则问题)【递归求解】

2018-03-27 20:30 225 查看
7. 描述:正则问题
考虑一种简单的正则表达式:
只由 x ( ) | 组成的正则表达式。
小明想求出这个正则表达式能接受的最长字符串的长度。 
例如 ((xx|xxx)x|(x|xx))xx 能接受的最长字符串是: xxxxxx,长度是6。
输入
一个由x()|组成的正则表达式。输入长度不超过100,保证合法。 
输出
这个正则表达式能接受的最长字符串的长度。 
例如,
输入:
((xx|xxx)x|(x|xx))xx 
程序应该输出:

题目分析:
    首先吐槽这个正则表达式居然不给解释。

    刚开始想的是用栈实现,但是想想有点麻烦。于是考虑用递归实现括号。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
string sh;
int i = 0;
int f()
{
int mx = 0;
int temp = 0;
int len = sh.length();

while( i < len)
{
if (sh[i] == '(')
{
i++;
temp = temp + f();
}
else if(sh[i] == ')')
{
i++;
break;
}
else if(sh[i] == '|')
{
i++;
mx = max(temp,mx);
temp = 0;
}
else
{
i++;
temp++;
}
}
return max(mx,temp);
}

int main()
{
cin>>sh;
cout<<f()<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: