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三个字符串,c的长度是a+b的长度,在a、b原先顺序不变的情况下,问是否能拼出c
思路:原以为是字符串匹配问题,结果是深搜。。
因为给出的a、b两个字符串的长度刚好等于第三个字符串的长度,所以可以dfs。所以当长度满足或者该字符已经用过就可以进行return。
搜索传入的是三个字符串的下标,根据下标进行判断。
最后跳出的条件就是c串的最后的一个字符要么是a串的最后一个字符,要么是b串的最后一个字符。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<iostream> 2 #include<stdio.h> 3 #include<string.h> 4 #include<algorithm> 5 #define inf 0x3f3f3f3f 6 using namespace std; 7 8 //3 9 //cat tree tcraete 10 //cat tree catrtee 11 //cat tree cttaree 12 13 //out 14 //Data set 1: yes 15 //Data set 2: yes 16 //Data set 3: no 17 18 string s1,s2,s3; 19 int ls1,ls2,ls3; 20 int flag; 21 int book[220][220]; 22 23 void dfs(int x,int y,int z)//传入下标 24 { 25 if(z==ls3)//长度找到之后 26 { 27 flag=1; 28 return; 29 } 30 if(flag==1||book[x][y]==1)//已经找到了或者该字符已经用过了 31 return; 32 book[x][y]=1; 33 if(x<ls1&&s1[x]==s3[z])//a的第x个字符跟c串的第z个字符相等 34 dfs(x+1,y,z+1);//加1就说明是按照顺序来的 35 if(y<ls2&&s2[y]==s3[z])//b的第y个字符跟c串的第z个字符相等 36 dfs(x,y+1,z+1); 37 return; 38 } 39 int main() 40 { 41 std::ios::sync_with_stdio(false); 42 cin.tie(0); 43 cout.tie(0); 44 int n; 45 cin>>n; 46 int t=1; 47 while(n--) 48 { 49 s1.erase(); 50 s2.erase(); 51 s3.erase(); 52 memset(book,0,sizeof(book)); 53 54 cin>>s1>>s2>>s3; 55 ls1=s1.length(); 56 ls2=s2.length(); 57 ls3=s3.length(); 58 59 flag=0; 60 dfs(0,0,0); 61 62 if(flag) 63 cout<<"Data set "<<dec<<t++<<": yes"<<endl; 64 else 65 cout<<"Data set "<<dec<<t++<<": no"<<endl; 66 } 67 return 0; 68 }