Orderly Class

托马斯女士管理着一个班级,她需要重新排列学生手中的字母卡片,通过选择并反转一部分连续的学生来达成目标。输入为两个字符串A和B,代表原始和目标顺序。计算能形成B的翻转方式数量,并在无法实现时返回0。样例展示了如何进行翻转操作。

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

Orderly Class

题目描述

Ms. Thomas is managing her class of n students.
She placed all her students in a line, and gave the i-th student from the left a card with the letter ai written on it.
She would now like to rearrange the students so that the i-th student from the left has a card with the letter bi written on it.
To do this, she will choose some consecutive group of students, and reverse their order. Students will hold on to their original cards during this process.
She’s now wondering, what is the number of valid ways to do this? (It may be impossible, in which case, the answer is zero).
With sequences abba and aabb, Ms. Thomas can choose the group a(bba). With sequences caxcab and cacxab, Ms. Thomas can choose ca(xc)ab or c(axca)b. With sequences a and z, there are clearly no solutions.

输入

The input is two lines of lowercase letters, A and B. The i-th character of A and B represent ai and bi respectively. It is guaranteed that A and B have the same positive length, and A and B are not identical. The common length is allowed to be as large as 100 000.

输出

For each test case, output a single integer, the number of ways Ms. Thomas can reverse some consecutive group of A to form the line specified by string B.

样例输入

abba
aabb

样例输出

1

题意

给出两个字符串让你选连续一段进行一次翻转,问有多少种翻转方式

题解思路

找出不同的子串的起始点,判断一下这段子串反转之后是否相等,如果不相等输出0;否则记ans=1,然后向两边扩展判断是否相等,每次判断如果两端的相等,ans++否则break;最后输出ans即可

附AC带码

include <bits/stdc++.h>

using namespace std;

int main()
{
    int n;
    char a[100005],b[100005];
    scanf("%s",a);
    scanf("%s",b);
    n = strlen(a);
    int minn,maxx;
    minn = n+1;
    maxx = -1;
    int f;
    for(int i=0;i<n;i++)
    {
        if(a[i]!=b[i])
        {
            minn = min(minn,i);
            maxx = max(maxx,i);
        }
    }
    f = 0;
    for(int i=minn,j=maxx;i<=maxx&&j>=minn;i++,j--)
    {
        if(a[i]!=b[j])
        {
            f = 1;
            break;
        }
    }
    if(f==1)
    {
        printf("0\n");
        return 0;
    }
    int ans = 1;
    for(int i=minn-1,j=maxx+1;i>=0&&j<n;i--,j++)
    {
        if(a[i]==a[j])
            ans++;
        else
            break;
    }
    printf("%d\n",ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值