Zipper
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".
InputThe 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.
OutputFor 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
题意:给出 A,B,C 三个字符串,问 A 不改变顺序的插入 B 中能否得到 C
因为长为 i 的字符串 A 和长为 j 的字符串 B 要能组成 C ,C的最后一个必定属于 A 或者 B
dp [i][j] 意为 dp[i][j] 意为 A的前i位,B的前j位能否组成C的前i+j位
dp[i][j] = (dp[i-1][j]&&A[i-1]==C[i+j-1])||(dp[i][j-1]&&B[j-1]==C[i+j-1]);
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include <iostream> 2 #include <stdio.h> 3 #include <string.h> 4 using namespace std; 5 #define MX 205 6 char A[MX],B[MX],C[MX*2]; 7 int dp[MX][MX]; //dp[i][j] 意为 A的前i位,B的前j位能否组成C的前i+j位 8 9 int main() 10 { 11 int T; 12 cin>>T; 13 for (int cnt=1;cnt<=T;cnt++) 14 { 15 scanf("%s %s %s",A,B,C); 16 int lena = strlen(A); 17 int lenb = strlen(B); 18 memset(dp,0,sizeof(dp)); 19 dp[0][0]=1; 20 for (int i=1;i<=lena;i++) 21 if (A[i-1]==C[i-1]&&dp[i-1][0]) 22 dp[i][0]=1; 23 for (int i=1;i<=lenb;i++) 24 if (B[i-1]==C[i-1]&&dp[0][i-1]) 25 dp[0][i]=1; 26 for (int i=1;i<=lena;i++) 27 for (int j=1;j<=lenb;j++) 28 dp[i][j] = (dp[i-1][j]&&A[i-1]==C[i+j-1])||(dp[i][j-1]&&B[j-1]==C[i+j-1]); 29 printf("Data set %d: ",cnt); 30 if (dp[lena][lenb]) 31 printf("yes\n"); 32 else 33 printf("no\n"); 34 } 35 return 0; 36 }