# HDU 6170-Two strings（DP）

www.MyException.Cn  网友分享于：2013-10-19  浏览：0次
HDU 6170----Two strings（DP）

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

```#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
const int N=2505;
char a[N],b[N];
int len1,len2;
int dp[N][N];

int main()
{
int T; cin>>T;
while(T--){
scanf("%s%s",a+1,b+1);
len1=strlen(a+1);
len2=strlen(b+1);
memset(dp,0,sizeof(dp));
dp[0][0]=1;
for(int i=1;i<=len2;i++)
{
if(b[i]=='.')
{
for(int j=0;j<=len1;j++)
{
if(dp[i-1][j]) dp[i][j+1]=1;
}
}
else if(b[i]=='*')
{
for(int j=0;j<=len1;j++)
{
if(dp[i-1][j])
{
dp[i][j]=1;
dp[i][j-1]=1;
while(a[j+1]==a[j]) dp[i][j+1]=1,j++;
}
}
}
else
{
for(int j=0;j<=len1;j++)
{
if(!dp[i-1][j]) continue;
if(a[j+1]==b[i]) dp[i][j+1]=1;
else if(b[i+1]=='*') dp[i+1][j]=1;
}
}
}
if(dp[len2][len1]) puts("yes");
else puts("no");
}
return 0;
}
/*
.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*
*/```

```#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
const int N=2505;
char a[N],b[N];
int len1,len2;
int h[N];
int c;
int dfs(int i,int j)
{
c++;
if(c>1000000) return 0;///默认为"no"的情况；
if(i<len1 && j>=len2) return 0;
if(i>=len1){
if(j>=len2) return 1;
if(j==len2-1 && b[j]=='*') return 1;
if(j==len2-1 && b[j]!='*') return 0;
if(j<len2-1){
if(b[j]=='*' && h[j+1]) return 1;
else if(b[j]!='*' && h[j]) return 1;
else return 0;
}
}
if(b[j]=='.') { b[j]=a[i]; int f=dfs(i+1,j+1); b[j]='.'; return f; }
if(b[j]=='*') {
if(a[i]==b[j-1]){
if(dfs(i+1,j)) return 1;
if(dfs(i,j+1)) return 1;
if(dfs(i-1,j+1)) return 1;
}
else {
if(dfs(i-1,j+1)) return 1;
if(dfs(i,j+1)) return 1;
}
}
if(a[i]==b[j]) return dfs(i+1,j+1);
else if(b[j+1]=='*') return dfs(i,j+2);
else return 0;
}

int main()
{
int T; cin>>T;
while(T--){
scanf("%s%s",a,b);
c=0;
len1=strlen(a);
len2=strlen(b);
int flag=1;
for(int i=len2-1;i>=0;i--)
{
if(!flag) h[i]=0;
else if(b[i]=='*'){
h[i]=1; h[i-1]=1; i--;
}
else{
h[i]=0;
flag=0;
}
}
int ans=dfs(0,0);
if(ans) puts("yes");
else puts("no");
}
return 0;
}
/*
.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*
*/```