LQ0109 正则问题DFS
Posted 海岛Blog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LQ0109 正则问题DFS相关的知识,希望对你有一定的参考价值。
题目来源:蓝桥杯2017初赛 C++ A组E题
题目描述
考虑一种简单的正则表达式:只由 x ( ) | 组成的正则表达式。
小明想求出这个正则表达式能接受的最长字符串的长度。
例如 ((xx|xxx)x|(x|xx))xx 能接受的最长字符串是: xxxxxx,长度是6
输入格式
输入一个由x()|组成的正则表达式。输入长度不超过100,保证合法。
输出格式
输出这个正则表达式能接受的最长字符串的长度。
输入样例
((xx|xxx)x|(x|xx))xx
输出样例
6
问题分析
简单的正则表达式,用DFS来实现。
AC的C++语言程序如下:
/* LQ0109 正则问题 */
#include <iostream>
using namespace std;
string s;
int pos = 0;
int dfs()
int ans = 0, t = 0;
while (s[pos])
if (s[pos] == '(')
pos++, t += dfs();
else if (s[pos] == ')')
pos++;
break;
else if (s[pos] == '|')
pos++;
ans = max(ans, t);
t = 0;
else
pos++, t++;
ans = max(ans, t);
return ans;
int main()
cin >> s;
cout << dfs() << endl;
return 0;
以上是关于LQ0109 正则问题DFS的主要内容,如果未能解决你的问题,请参考以下文章