Description
For example, consider forming "tcraete" from "cat" and "tree":
String A: cat
String B: tree
String C: tcraete
As you can see, we can form the third string by alternating characters from the two strings. As a second example, consider forming "catrtee" from "cat" and "tree":
String A: cat
String B: tree
String C: catrtee
Finally, notice that it is impossible to form "cttaree" from "cat" and "tree".
Input
For each data set, the line of input consists of three strings, separated by a single space. All strings are composed of upper and lower case letters only. The length of the third string is always the sum of the lengths of the first two strings. The first two strings will have lengths between 1 and 200 characters, inclusive.
Output
Data set n: yes
if the third string can be formed from the first two, or
Data set n: no
if it cannot. Of course n should be replaced by the data set number. See the sample output below for an example.
Sample Input
3
cat tree tcraete
cat tree catrtee
cat tree cttaree
Sample Output
Data set 1: yes
Data set 2: yes
Data set 3: no
【题意】给出三个字符串,求前两个是否包含在第三个中。
【思路】之前用过dfs,这次用dp,检验dp[len1][len2]是否为1;
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int N=;
int dp[N][N];
int main()
{
int n;
char a[N],b[N],c[N];
int cas=;
while(~scanf("%d",&n))
{
cas++;
memset( dp,,sizeof(dp));
scanf("%s%s%s",a+,b+,c+);
int len1=strlen(a+);
int len2=strlen(b+);
int len3=strlen(c+);
for(int i=;i<=len1;i++)
{
if(a[i]==c[i]) dp[i][]=;
else break;
}
for(int j=;j<=len2;j++)
{
if(b[j]==c[j])
dp[][j]=;
else break;
}
for(int i=;i<=len1;i++)
{
for(int j=;j<=len2;j++)
{
if(c[i+j]==a[i]&&dp[i-][j])
dp[i][j]=;
if(c[i+j]==b[j]&&dp[i][j-])
dp[i][j]=;
}
}
printf("Data set %d: ",cas);
if(dp[len1][len2]) printf("yes\n");
else printf("no\n");
}
return ;
}