Your task is to judge whether the input is a legal regular expression.
A regular expression is defined as follow:
1: 0 and 1 are both regular expressions.
2: If P and Q are regular expressions, PQ is a regular expression.
3: If P is a regular expression, § is a regular expression.
4: If P is a regular expression, P* is a regular expression.
5: If P and Q are regular expressions, P|Q is a regular expression.
Input
The input contains multiple testcases.
Each test case is a single line with a string not containing space.The length of the string is less than 100.
Output
For each testcase, print yes if the input is a regular expression, otherwise print no.
Sample Input
010101101*
(11|0*)*
)*111
Sample Output
yes
yes
no
题目链接
这是一个区间dp的题目,直接套用模板做的,只要区间内符合上面的条件便是符合表达式,一点一点的推出来。
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int main()
{
char str[105];
int dp[105][105];
while(~scanf("%s", &str))
{
int len = strlen(str);
memset(dp, 0, sizeof(dp));
//0和1都是正则表达式,每一个区间占一个格
for(int i = 0; i < len; i++)
if(str[i] == '0' || str[i] == '1')
dp[i][i] = 1;
for(int l = 1; l < len; l++)
for(int i = 0; i + l < len; i++)
{
int j = i + l;
//两侧是括号,中间是正则表达式
if(str[i] == '(' && str[j] == ')' && dp[i + 1][j - 1])
dp[i][j] = 1;
//前面部分是正则表达式,后面加*
if(str[j] == '*' && dp[i][j - 1])
dp[i][j] = 1;
for(int k = i; k < j; k++)
{
//乘法
if(dp[i][k] && dp[k + 1][j]) dp[i][j] = 1;
// ‘|’运算,两侧都是正则表达式
if(dp[i][k] && str[k + 1] == '|' && dp[k + 2][j]) dp[i][j] = 1;
}
}
if(dp[0][len - 1]) printf("yes\n");
else printf("no\n");
}
return 0;
}