题目描述 点击打开链接
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.
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;
}

本文介绍了一种通过翻转字符串中某段连续字符来匹配目标字符串的方法。算法首先确定源字符串与目标字符串不同的起始与结束位置,接着验证是否可以通过翻转这段不同部分使源字符串与目标字符串匹配。最后通过扩展两端相同字符来增加匹配的可能性。
1491

被折叠的 条评论
为什么被折叠?



