HihoCoder - 1110 - Regular Expression(区间dp )

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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值