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
程序应该输出:
6
题目分析:
首先吐槽这个正则表达式居然不给解释。
刚开始想的是用栈实现,但是想想有点麻烦。于是考虑用递归实现括号。
#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;
}
考虑一种简单的正则表达式:
只由 x ( ) | 组成的正则表达式。
小明想求出这个正则表达式能接受的最长字符串的长度。
例如 ((xx|xxx)x|(x|xx))xx 能接受的最长字符串是: xxxxxx,长度是6。
输入
一个由x()|组成的正则表达式。输入长度不超过100,保证合法。
输出
这个正则表达式能接受的最长字符串的长度。
例如,
输入:
((xx|xxx)x|(x|xx))xx
程序应该输出:
6
题目分析:
首先吐槽这个正则表达式居然不给解释。
刚开始想的是用栈实现,但是想想有点麻烦。于是考虑用递归实现括号。
#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;
}
相关文章推荐
- 使用C++递归求解跳台阶问题
- 非递归求解N皇后问题(回溯法)
- 全排列问题之递归求解
- 关于n皇后问题的递归求解,有详细的步骤说明。
- 递归求解排队进电影院问题,附带JAVA代码
- 递归求解8皇后问题
- 关于正则表达式的递归匹配问题
- 递归求解几类排列组合问题(一、类循环组合排列)
- 递归求解几类排列组合问题(六、非重复生成全子集组合排列)
- 递归练习-House Robber问题求解
- 迷宫求解问题-递归(栈的应用)
- 递归求解迷宫问题
- 约瑟夫问题递归求解
- 汉诺塔问题递归求解(python)
- 利用递归来求解迷宫问题
- 背包问题的递归与非递归求解
- 用递归方法求解汉诺塔问题。
- 约瑟夫环问题的两种解决方式(递归求解和数组模拟求解)
- rnqoj 拔河问题 一重背包问题(递归求解,dp求解)
- 背包问题选中递归求解0 1背包问题