我总感觉这题我写过题解的,但是为啥不见了呢?
Combine String
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)Total Submission(s): 665 Accepted Submission(s): 214
Problem Description
Given three strings
a
,
b
and
c
, your mission is to check whether
c
is the combine string of
a
and
b
.
A string c is said to be the combine string of a and b if and only if c can be broken into two subsequences, when you read them as a string, one equals to a , and the other equals to b .
For example, ``adebcf'' is a combine string of ``abc'' and ``def''.
A string c is said to be the combine string of a and b if and only if c can be broken into two subsequences, when you read them as a string, one equals to a , and the other equals to b .
For example, ``adebcf'' is a combine string of ``abc'' and ``def''.
Input
Input file contains several test cases (no more than 20). Process to the end of file.
Each test case contains three strings a , b and c (the length of each string is between 1 and 2000).
Each test case contains three strings a , b and c (the length of each string is between 1 and 2000).
Output
For each test case, print ``Yes'', if
c
is a combine string of
a
and
b
, otherwise print ``No''.
Sample Input
abc def adebcf abc def abecdf
Sample Output
Yes No
这道题目我还记得六月份我写的时候不是用DP写的,所以会TLE,我直接用递归来暴力,但是如果有的字符是相同的,就出现多种情况,走着走着可能就要回溯到某一步,这就很浪费时间,所以应该采取用空间换时间的动态规划算法。我们可以建立一个二维数组G,G的行 i 列 j 数是代表a的前i个成功匹配到了c,b的前j个成功匹配到了c,合起来就是a和b成功匹配了i+j-1个c字符,最后只要检验这个二维数组G【len_a】【len_b】这个点是否等于1,就知道能不能匹配到了。
代码如下:
#include<stdio.h>
#include<string.h>
int G[2005][2005];
int main()
{
int len_a,len_b,len_c,i,j;
char a[2005],b[2005],c[4005];
while(scanf("%s%s%s",a,b,c)!=EOF)
{
len_a=strlen(a);
len_b=strlen(b);
len_c=strlen(c);
if(len_a+len_b!=len_c)
{
puts("No");
continue;
}
memset(G,0,sizeof(G));
G[0][0]=1;
for(i=1;i<=len_a;i++)
{
if(a[i-1]==c[i-1]&&G[0][i-1])
G[0][i]=1;
else
break;
}
for(i=1;i<=len_b;i++)
{
if(b[i-1]==c[i-1]&&G[i-1][0])
G[i][0]=1;
else
break;
}
for(i=1;i<=len_b;i++)
{
for(j=1;j<=len_a;j++)
{
if( (G[i-1][j]&&b[i-1]==c[i+j-1]) || (G[i][j-1]&&a[j-1]==c[i+j-1]))
{
G[i][j]=1;
}
}
}
if(G[len_a][len_b])
{
printf("Yes\n");
}
else
printf("No\n");
}
}
题目是不难,但是六月份的时候我没写出来,我当时写了题解后,今天再看一次,发现还是没思路,只好问学长,给了我一个思路,30分钟就写出来了,所以复习错题是很有必要的!