这一道相当经典的题目,由于这道题目的数据较弱。用判断最后合成的字符串的最后一个字符与两个字串的最后一个字符是否相同,不同的话就剪枝。
另外的方法是如下的递推式
用a,b代表两个字串 ,c代表目标字符串
f(i,j)表示能否用a[0,i-1]与b[0,j-1]按照题目要求组成c[0,i+j-1]
初始条件:f(0,0)=1
1:if(j>=1,c[i+j-1]==b[j-1] )
f(i,j)=f(i,j)||f(i,j-1)
2:if(i>=1 && c[j+i-1]==a[i-1])
f(i,j)=f(i,j)||f(i-1,j)
最终判断f(la,lb)的值即可。
Language:
Zipper
Description
Given three strings, you are to determine whether the third string can be formed by combining the characters in the first two strings. The first two strings can be mixed arbitrarily, but each must stay in its original order.
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
The first line of input contains a single positive integer from 1 through 1000. It represents the number of data sets to follow. The processing for each data set is identical. The data sets appear on the following lines, one data set per line.
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
For each data set, print:
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 Source |
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<ctime>
using namespace std;
int n;
char a[1200],b[1200],c[1200];
bool jud[1200][1200];
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%s%s%s",a,b,c);
int la,lb,lc;
la=strlen(a);
lb=strlen(b);
lc=strlen(c);
// if(c[lc-1]!=a[la-1] && c[lc-1]!=b[lb-1])
//{
// printf("Data set %d: no\n",i);
//continue;
//}
memset(jud,0,sizeof(jud));
jud[0][0]=1;
if(a[0]==c[0]) jud[1][0]=1;
if(b[0]==c[0]) jud[0][1]=1;
for(int j=0;j<=la;j++)
{
for(int k=0;k<=lb;k++)
{
if(k>=1 && c[j+k-1]==b[k-1] )
jud[j][k]=jud[j][k]||jud[j][k-1];
if(j>=1 && c[j+k-1]==a[j-1])
jud[j][k]=jud[j][k]||jud[j-1][k];
}
}
printf("Data set %d: ",i);
jud[strlen(a)][strlen(b)]?printf("yes\n"):printf("no\n");
}
return 0;
}