1225. 正则问题

题目链接

1225. 正则问题

考虑一种简单的正则表达式:

只由 x ( ) | 组成的正则表达式。

小明想求出这个正则表达式能接受的最长字符串的长度。

例如 ((xx|xxx)x|(x|xx))xx 能接受的最长字符串是: xxxxxx,长度是6。

输入格式

一个由x()|组成的正则表达式。

输出格式

输出所给正则表达式能接受的最长字符串的长度。

数据范围

输入长度不超过100,保证合法。

输入样例:

((xx|xxx)x|(x|xx))xx 

输出样例:

6

解题思路

递归,dfs

显然,先算括号里面的,遇到 \(|\) 取两边max,遇到 \(x\) 直接加上,关键在于dfs的写法

  • 时间复杂度:\(O(n)\)

代码

// Problem: 正则问题
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/1227/
// Memory Limit: 64 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

// %%%Skyqwq
#include <bits/stdc++.h>
 
//#define int long long
#define help {cin.tie(NULL); cout.tie(NULL);}
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
using namespace std;
 
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
 
template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
 
template <typename T> void inline read(T &x) {
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
    while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
    x *= f;
}

int n,i;
string s;
int dfs()
{
	int res=0;
	while(i<n)
	{
		if(s[i]=='(')
		{
			i++;
			res+=dfs();
			i++;
		}
		else if(s[i]==')')break;
		else if(s[i]=='|')
		{
			i++;
			res=max(res,dfs());
		}
		else
		{
			i++;
			res++;
		}
	}
	return res;
}
int main()
{
    cin>>s;
    n=s.size();
    cout<<dfs();
    return 0;
}
posted @ 2022-02-16 10:46  zyy2001  阅读(49)  评论(0)    收藏  举报