CF 523C (字符串处理)

本文介绍了一个算法问题,即如何确定一个给定的长字符串能够被切割成两部分,每部分通过删除某些字符后都能匹配一个指定的标准字符串。文章提供了一种高效的方法来解决这个问题,并附带了具体的实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



Description

A Martian boy is named s — he has got this name quite recently from his parents for his coming of age birthday. Now he enjoys looking for his name everywhere. If he sees that he can obtain his name from some string by removing zero or more letters (at that, the remaining letters remain in the same order), he gets happy. For example, if saba», then strings «baobab», «aabbaa», «helloabahello» make him very happy and strings «aab», «baaa» and «helloabhello» do not.

However rather than being happy once, he loves twice as much being happy twice! So, when he got string t as a present, he wanted to cut it in two parts (the left part and the right part) so that each part made him happy.

Help s determine the number of distinct ways to cut the given string t into two parts in the required manner.

Input

The first line contains string s, consisting of lowercase English letters. The length of string s is from 1 to 1000 letters.

The second line contains string t, that also consists of lowercase English letters. The length of string t is from 1 to 106 letters.

Output

Print the sought number of ways to cut string t in two so that each part made s happy.

Input
aba
baobababbah
Output
2
Input
mars
sunvenusearthmarsjupitersaturnuranusneptune
Output
0

题目大意:给定一个标准字符串和一个待处理字符串,问是否可以将这个字符串切成两截,使得每一截删掉若干个字符以后都可以得到标准字符串,求出方案个数。
其实仔细想一想,可以从头开始搜一次,记下从头开始搜到的发现标准字符串的位置flag1,再从尾开始向前搜一次,搜到的发现标准字符串的位置flag2,再用flag2-flag1,如果小于零说明找不到,大于零则输出(因为位于flag1与flag2之间的所有位置都可以满足要求)。
如果一个一个字符地截是铁定超时的。
代码:
#include <iostream>
#include <string.h>
#include <stdio.h>

using namespace std;

int main()
{
    char s[1002],t[1000002];
    int start,i,j,len1,len2,end0,flag1,flag2,ans;
    gets(s);
    gets(t);
    len1=strlen(s);
    len2=strlen(t);
    start=0;
    for (j=0;j<=len1-1;j++)
    {
        for (i=start;i<=len2-1;i++)
        {
            if (s[j]==t[i])
            {
                start=i+1;
                break;
            }
        }
    }
    flag1=start-1;
    end0=len2-1;
    for (j=len1-1;j>=0;j--)
    {
        for (i=end0;i>=0;i--)
        {
            if (s[j]==t[i])
            {
                end0=i-1;
                break;
            }
        }
    }
    flag2=end0+1;
    ans=flag2-flag1;
    if (ans<=0)
    {
        printf("0");
    }
    else
    {
        printf("%d",ans);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值