E - Substring Reverse

本文介绍了一种算法,用于判断是否能通过反转一个给定字符串的某个子串使其与目标字符串相等。通过前后查找不匹配字符并比较反转后的子串,实现高效匹配。

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

Two strings s and t of the same length are given. Determine whether it is possible to make t from s using exactly one reverse of some its substring.

Input
The first line contains the string s, and the second — the string t. Both strings have the same length from 1 to 200000 characters and consist of lowercase Latin letters.

Output
Output «YES», if it is possible to reverse some substring of s to make s equal to t, and «NO», otherwise.

Examples
Input
abcdefg
abedcfg
Output
YES
Input
abcdefg
abdecfg
Output
NO
思路:从前开始找到不一样字母的下标,再从后找到不一样字母的下标。

#include<bits/stdc++.h>
using namespace std;
const int maxx=2e5+10;
char a[maxx],b[maxx];
int main()
{
    std::ios::sync_with_stdio(false);
    cin>>a>>b;
    int len=strlen(a);
    int n1=-1,n2=-1;
    for(int i=0; i<len; i++)
    {
        if(a[i]!=b[i])
        {
            n1=i;
            break;
        }
    }
    for(int i=len-1; i>=0; i--)
    {
        if(a[i]!=b[i])
        {
            n2=i;
            break;
        }
    }
    int flag=1;
    for(int i=n1; i<=n2; i++)
    {
        if(a[i]!=b[n2+n1-i])
        {
            flag=0;
            // cout<<i<<"&&&&"<<j<<endl;
            break;
        }
    }
    if(flag==1)
        cout<<"YES"<<endl;
    else
        cout<<"NO"<<endl;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值