HDU 6170 字符串Dp

16 篇文章 0 订阅

Two strings

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1222    Accepted Submission(s): 507


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
 

题意 : 字符串匹配问题 ' . ' 可以匹配任意字符, ‘ * ’ 可以匹配空,或者前面的字符,且可以匹配多个

比如 a * 可以匹配 aaa 和 aaaaaaa等等

这个题贪心是贪不过的,用DP可以,而且字符串长 2500 ,n方的复杂度是允许的

dp[i][j]表示b[i]

对于 ' . ' ,它可以匹配任意字符,所以DP[i[[j] = DP[i - 1][j - 1]

对于' * ' ,它匹配一个的时候状态来自 DP[i - 1][j]  匹配 0 个的时候来自 DP[i - 2][j]

并且 

if((dp[i - 1][j - 1] || dp[i][j - 1]) && a[j - 1] == a[j]){
dp[i][j] = 1;
}

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<string.h>
using namespace std;
#define maxn 2600
int dp[maxn][maxn];
char a[maxn],b[maxn];
int n;
int main(){
	scanf("%d",&n);
	getchar();
	while(n--){
		memset(dp,0,sizeof(dp));
		gets(a + 1);
		gets(b + 1);
		int lena = strlen(a + 1);
		int lenb = strlen(b + 1);
		dp[0][0] = 1;
		for(int i = 1;i <= lenb;i++){
			if(i == 2 && b[i] == '*')
				dp[i][0] = 1;
			for(int j = 1;j <= lena;j++){
				if(b[i] == '.' || a[j] == b[i]){
					dp[i][j] = dp[i - 1][j - 1];
				}else if(b[i] == '*'){
					dp[i][j] = dp[i - 1][j] | dp[i - 2][j];
					if((dp[i - 1][j - 1] || dp[i][j - 1]) && a[j - 1] == a[j]){
						dp[i][j] = 1;
					}
				}
			}
		}
		puts(dp[lenb][lena]?"yes":"no");
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值