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

一、题目

给你两个字符串 a 和 b ,它们长度相同。请你选择一个下标,将两个字符串都在 相同的下标 分割开。由 a 可以得到两个字符串: aprefix 和 asuffix ,满足 a = aprefix + asuffix ,同理,由 b 可以得到两个字符串 bprefix 和 bsuffix ,满足 b = bprefix + bsuffix 。请你判断 aprefix + bsuffix 或者 bprefix + asuffix 能否构成回文串。

二、思路

当遇到不相等的情况时,则说明遇到了分割点,分割的位置可能是左侧的指针,也可能是右侧的指针。如果分割点是左侧的指针,则需要 b 在双指针之间的字符串构成回文;如果分割点是右侧的指针,则需要 a 在双指针之间的字符串构成回文。这二者满足其一即可。

三、代码

class Solution {
public:
    bool checkSelfPalindrome(const string &a, int left, int right) {
        while (left < right && a[left] == a[right]) {
            left++;
            right--;
        }
        return left >= right;
    }

    bool checkConcatenation(const string &a, const string &b) {
        int n = a.size();
        int left = 0, right = n - 1;
        while (left < right && a[left] == b[right]) {
            left++;
            right--;
        }
        if (left >= right) {
            return true;
        }
        return checkSelfPalindrome(a, left, right) || checkSelfPalindrome(b, left, right);
    }

    bool checkPalindromeFormation(string a, string b) {
        return checkConcatenation(a, b) || checkConcatenation(b, a);
    }
};

四、分析

  • 时间复杂度:O(n),其实 n 是输入字符串的长度。每个字符串最多遍历两遍。

  • 空间复杂度:O(1),仅使用常数空间。

posted @ 2023-03-19 21:27  ImreW  阅读(2)  评论(0编辑  收藏  举报