交替字符串

题目详情

如果字符串str3能够由str1和str2中的字符按顺序交替形成,那么称str3为str1和str2的交替字符串。例如str1="abc",str2="def",那么"adbecf", "abcdef", "abdecf", "abcdef", "adefbc"等等都为str1和str2的交替字符串。更形式化的,str3的生成算法如下:

str3=""

while str1不为空 or str2不为空:

 把str1或str2的首字符加入到str3,并从str1或str2中删除相应的字符

end

给定str1, str2,和str3,判断str3是否为str1和str2的交替字符串。


输入格式:

多组数据,每组数据三行,分别是str1,str2,str3。str1,str2的长度在[1..100]范围内,str3的范围在[1..200]范围内。字符串只包含小写英文字母。

输出格式:

每组数据输出一行YES或者NO。

答题说明

输入样例

a

b

ab

a

b

ca

输出样例:

YES

NO


思路: 代码比较短。


代码:


#include <iostream>
#include <climits>
#include <cmath>
#include <algorithm>
#include <iomanip>
#include <vector>

#define inf 0x7fffffff
#define MOD 1000000007
using namespace std;

char s1[110], s2[110], s3[220];
bool dp[110][110];

int main() {
    while(gets(s1+1)) {
        gets(s2+1);
        gets(s3+1);

        int l1 = strlen(s1+1);
        int l2 = strlen(s2+1);
        int l3 = strlen(s3+1);

        if(l1+l2 != l3) {
            printf("NO\n");
        } else {
            fill_n(&dp[0][0], sizeof(dp)/sizeof(dp[0][0]), false);
            dp[0][0] = true;
            int i, j, k;
            for(i=0; i<=l1; i++) {
                for(j=0; j<=l2; j++) {
                    if(i > 0 && s1[i] == s3[i+j]) {
                        dp[i][j] = dp[i-1][j];
                    }
                    if(j > 0 && s2[j] == s3[i+j]) {
                        dp[i][j] = (dp[i][j] || dp[i][j-1]);
                    }
                }
            }
            if(dp[l1][l2])
                printf("YES\n");
            else
                printf("NO\n");
        }
    }

    return 0;
} 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值