2013
11-10

# Zipper

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”.

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.

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.

3
cat tree tcraete
cat tree catrtee
cat tree cttaree


Data set 1: yes
Data set 2: yes
Data set 3: no


import java.io.BufferedReader;
import java.util.StringTokenizer;

public class Main{

public static void main(String[] args) throws Exception{

for(int a=1;a<=n;a++){
StringTokenizer toke = new StringTokenizer(strTemp);
String str1 = toke.nextToken();
String str2 = toke.nextToken();
String str = toke.nextToken();
int length1 = str1.length();
int length2 = str2.length();
//array[i][j]琛ㄧずstr1[i]��tr2[j]�藉�缁��str[i+j]
boolean array[][] = new boolean[length2+1][length1+1];
for(int i=1;i<=length1;i++){
if(str1.substring(0, i).equals(str.substring(0,i)))
array[0][i] = true;
else
array[0][i] = false;
}
for(int i=1;i<=length1;i++){
if(str2.substring(0, i).equals(str.substring(0,i)))
array[i][0] = true;
else
array[i][0] = false;
}

for(int i=1;i<=length2;i++){
for(int j=1;j<=length1;j++){
if(array[i][j-1]&&str1.charAt(j-1)==str.charAt(i+j-1)||array[i-1][j]&&str2.charAt(i-1)==str.charAt(i+j-1))
array[i][j] = true;
else
array[i][j] = false;
}
}
if(array[length2][length1])
System.out.println("Data set "+a+": yes");
else
System.out.println("Data set "+a+": no");
}
}
}

1. “可以发现,树将是满二叉树,”这句话不对吧，构造的树应该是“完全二叉树”，而非“满二叉树”。