1616. 分割两个字符串得到回文串

题意

给定两个长度相同的字符串,问能否切割两个字符串的相同位置,再进行组合,得到一个回文串。

思路

  1. 首先从串a首、串b尾开始配对,检索是否对称
  2. 如果不对称,尾指针上浮到串a继续检索
  3. 如果不对称,两个指针同时下沉到串b继续检索

如果中间任意一个检索,让指针走到了length/2的位置,即可得到回文串。

完成上述操作后,重置指针为串a尾串b首继续搜索一遍。

solution

#include <bits/stdc++.h>
#define sc(x) scanf("%lld", &(x))
#define pr(x) printf("%lld\n", x)
using namespace std;
typedef long long ll;
const int N = 1e5 + 7;
const ll mod = 1e9 + 7;
bool chk(string s) {
    int n = s.length();
    for (int i = 0; i < n / 2; ++i) {
        if (s[i] != s[n - 1 - i]) return 0;
    }
    return 1;
}
bool checkPalindromeFormation(string a, string b) {
    int n = a.length();
    if (chk(a) || chk(b)) return 1;
    if (a[0] != b[n - 1] && a[n - 1] != b[0]) return 0;
    int L = 0, R = n - 1;
    while (L < R && a[L] == b[R]) {
        ++L, --R;
        if (L == n / 2) return 1;
    }
    while (L < R && a[L] == a[R]) {
        ++L, --R;
        if (L == n / 2) return 1;
    }
    while (L < R && b[L] == b[R]) {
        ++L, --R;
        if (L == n / 2) return 1;
    }
    L = n - 1, R = 0;
    while (L > R && a[L] == b[R]) {
        --L, ++R;
        if (R == n / 2) return 1;
    }
    while (L > R && a[L] == a[R]) {
        --L, ++R;
        if (R == n / 2) return 1;
    }
    while (L > R && b[L] == b[R]) {
        --L, ++R;
        if (R == n / 2) return 1;
    }
    return 0;
}
int main() {
    string s, t;
    while (cin >> s >> t) cout << checkPalindromeFormation(s, t) << endl;
    return 0;
}
// abdef fecab
// cdeoo oooab
// pvhmupgqeltozftlmfjjde yjgpzbezspnnpszebzmhvp
算法竞赛之路 文章被收录于专栏

整理、记录算法竞赛的好题

全部评论

相关推荐

程序员小白条:太晚了,看别人找到实习了才投的话,自己本身就没啥准备,计划太晚咯,只能吞苦果子
点赞 评论 收藏
分享
zzzzhz:兄弟你先猛猛投简历至少三百家,能约到面试就去面。最近可以速成智能小车,智慧家居烂大街的项目,不需要自己写,只需要把里面的代码讲解看明白就行。把其中涉及到的八股文都拿出来单独背一下,我去年找工作就一个智能小车智慧家居找了10k差不多。
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务