HDU 6170Two strings

本文介绍了一种使用动态规划解决正则表达式匹配问题的方法。通过构建二维DP数组来判断两个字符串是否匹配,其中涉及特殊字符'.'和'*'的处理逻辑。最终实现了对于包含特定正则表达式的字符串的有效匹配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem Description
Giving two strings and you should judge if they are matched.
The first string contains lowercase letters and uppercase letters.
The second string contains lowercase letters, uppercase letters, and special symbols: “.” and “*”.
. can match any letter, and * means the front character can appear any times. For example, “a.b” can match “acb” or “abb”, “a*” can match “a”, “aa” and even empty string. ( “*” will not appear in the front of the string, and there will not be two consecutive “*”.
 

 

Input
The first line contains an integer T implying the number of test cases. (T≤15)
For each test case, there are two lines implying the two strings (The length of the two strings is less than 2500).
 

 

Output
For each test case, print “yes” if the two strings are matched, otherwise print “no”.
 

 

Sample Input
3
aa
a*
abb
a.*
abb
aab
 

 

Sample Output
yes
yes
no
正则表达式的问题。
题解说的是用动态规矩。
str表示主串,str1表示模拟串,可以假设dp[i][j]表示str1[1,i]和str[1,j]是否匹配。
显然dp[0][0] = true.
str1[i] == . 或者str1[i] == str[j]时,dp[i][j] 看状态dp[i-1][j-1]
str1[i] == '*'时,dp[i][j] == dp[i-1][j] | dp[i-2][j],而当(dp[i-1][j-1] || dp[i][j-1]) && str[j-1] == str[j] 时,dp[i][j]必定为true;
详细参考
 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <string.h>
 4 #include <algorithm>
 5 using namespace std;
 6 const int N = 2510;
 7 char str[N], str1[N];
 8 bool dp[N][N];
 9 int main() {
10     int t;
11     scanf("%d", &t);
12     while(t--) {
13         memset(dp, false, sizeof(dp));
14         scanf("%s %s",str+1, str1+1);
15         int len = strlen(str+1), len1 = strlen(str1+1);
16         dp[0][0] = true;
17         for(int i = 1; i <= len1; i ++) {
18             if(i == 2 && str1[i] == '*') dp[i][0] = true;
19             for(int j = 1; j <= len; j ++) {
20                 if(str1[i] == '.' || str1[i] == str[j])
21                     dp[i][j] = dp[i-1][j-1];
22                 else if(str1[i] == '*') {
23                     dp[i][j] = dp[i-2][j] | dp[i-1][j];
24                     if((dp[i-1][j-1] || dp[i][j-1]) && str[j-1] == str[j])
25                         dp[i][j] = true;
26                 }
27             }
28         }
29         printf("%s\n",dp[len1][len]?"yes":"no");
30     }
31     return 0;
32 }

 

转载于:https://www.cnblogs.com/xingkongyihao/p/7413929.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值