Combine String

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

Output

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

Sample Input

abc
def
adebcf
abc
def
abecdf

Sample Output

Yes
No

题意:给a,b,c三个串,看c,能否由a,b构成

思路:dp[i][j]表示c的前i+j个字符,能否由a的前i个,b的前j个构成,dp[0][0]=1(用1表示能构成)

状态转移:当a[i]==c[i+j]时,考虑dp[i-1][j],

                 当b[j]=c[i+j]时,考虑dp[i][j-1]

代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <map>
#include <vector>
#include <set>
#include <string>
#include <math.h>
#include <stack>
typedef long long ll;
const int maxn=1e5+10;
using namespace std;
char a[maxn],b[maxn],s[maxn];
int dp[2005][2005];
int main(int argc, char const *argv[])
{
    while(scanf("%s%s%s",a,b,s)!=EOF)
    {
        int la=strlen(a),lb=strlen(b),ls=strlen(s);
        //memset(dp,0,sizeof(dp));
        dp[0][0]=1;
        for(int i=0;i<=la;i++)
        {
            for(int j=0;j<=lb;j++)
            {
                if(i && j) dp[i][j] = 0; 
                if(i)
                {
                    dp[i][j]=dp[i-1][j]&(a[i-1]==s[i+j-1]);//注意从0开始,需要减一
                }
                if(j)
                {
                    dp[i][j]|=dp[i][j-1]&(b[j-1]==s[i+j-1]);
                }
            }
        }
        if(dp[la][lb]==1&&la+lb==ls)
        {
            cout<<"Yes"<<endl;
        }
        else
        {
            cout<<"No"<<endl;
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40774175/article/details/81318770