Combine String(思维)

Problem Description
Given three strings , and , your mission is to check whether is the combine string of and .
A string is said to be the combine string of and if and only if can be broken into two subsequences, when you read them as a string, one equals to , and the other equals to .
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 , and (the length of each string is between 1 and 2000).
 

Output
For each test case, print ``Yes'', if is a combine string of and , otherwise print ``No''.
 

Sample Input

abc

def

adebcf 

abc 

def 

abecdf

直接用递归来暴力,但是如果有的字符是相同的,就出现多种情况,走着走着可能就要回溯到某一步,这就很浪费时间,所以应该采取用空间换时间的动态规划算法。我们可以建立一个二维数组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>
char a[2010],b[2010],c[2010];
int maze[2010][2010];
int main()
{	
	int i,j,la,lb,lc;
	while(scanf("%s %s %s",a,b,c)!=EOF){
		la=strlen(a);
		lb=strlen(b);
		lc=strlen(c);
		
		if(lc!=(la+lb)){
			printf("No\n");
			continue;
		}
		
		memset(maze,0,sizeof(maze));
		maze[0][0]=1;
		
		for(i=1;i<=la;i++){
			if(a[i-1]==c[i-=1]&&maze[0][i-1]==1)
				maze[0][i]=1;
			else
				break;
		}
		
		for(i=1;i<=lb;i++){
			if(b[i-1]==c[i-1]&&maze[i-1][0]==1)
				maze[i-1][0]=1;
			else
				break;
		}
		
		for(i=1;i<=lb;i++){
			for(j==1;j<=la;j++){
				if((maze[i-1][j]==1&&a[j-1]==c[i+j-1])||(maze[i][j-1]==1&&b[i-1]==c[i+j-1]))
					maze[i][j]=1;
				else
					break;
			}
		}
		
		if(maze[la][lb]==1)
			printf("Yes\n");
		else
			printf("No\n");
	}
	
	return 0;
}

 
  

 

Sample Output

猜你喜欢

转载自blog.csdn.net/dong_qian/article/details/80709650