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

题意:在数组a中选取连续的一段,颠倒顺序,使其变为b(只能选一组,颠倒一次),问有几种颠倒方法

思路:找到a,b不相同的左端点和右端点,如果a的此段可以经过翻转得到b,对a扩增即可

#include <stdio.h>
#include <string.h>
int main()
{
    char a[100010],b[100010];
    scanf("%s%s",a,b);
    int len=strlen(a);
    int l=0,r=len-1;
    while(a[l]==b[l])
        l++;
    while(a[r]==b[r])
        r--;
    for(int p=l,q=r;p<=r;p++,q--)   
    {
        if(a[p]!=b[q])
        {
            puts("0");
            return 0;
        }
    }
    int ans=0;
    while(l-ans-1>=0&&r+ans+1<len&&a[l-ans-1]==a[r+ans+1])
        ans++;
    printf("%d\n",ans+1);
    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

2020/3/16

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值