Zipper
Problem 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".
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".
题意大概就是给三个字符串,第三个字符串是由前两个字符串组成的,但是不能改变字母在原字符串中的前后相对位置。
输入:
第一行一个整数,测试数据的个数,之后每行三个字符串,分别用空格隔开。
输出:
格式为:Data set 1: yes若第三个字符串符合要求则为yes,否则为no。
注:字符串c中的每个字符只能用一次。运用递归函数进行搜索。
#include<stdio.h>
#include<string.h>
int n,lena,lenb,lenc,v[201][201];
char a[201],b[201],c[401];
int dfs(int i,int j,int k)
{
if(c[k]=='\0')return 1;
if(v[i][j])return 0;//每个字符用一次
v[i][j]=1;
if(a[i]==c[k]&&dfs(i+1,j,k+1))return 1;//递归
if(b[j]==c[k]&&dfs(i,j+1,k+1))return 1;
return 0;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;++i)
{
scanf("%s%s%s",a,b,c);
printf("Data set %d: ",i);
memset(v,0,sizeof(v));
lena=strlen(a);
lenb=strlen(b);
lenc=strlen(c);
if(dfs(0,0,0))printf("yes\n");
else printf("no\n");
}
return 0;
}