Skip to content

Latest commit

 

History

History

1616

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

You are given two strings a and b of the same length. Choose an index and split both strings at the same index, splitting a into two strings: aprefix and asuffix where a = aprefix + asuffix, and splitting b into two strings: bprefix and bsuffix where b = bprefix + bsuffix. Check if aprefix + bsuffix or bprefix + asuffix forms a palindrome.

When you split a string s into sprefix and ssuffix, either ssuffix or sprefix is allowed to be empty. For example, if s = "abc", then "" + "abc", "a" + "bc", "ab" + "c" , and "abc" + "" are valid splits.

Return true if it is possible to form a palindrome string, otherwise return false.

Notice that x + y denotes the concatenation of strings x and y.

 

Example 1:

Input: a = "x", b = "y"
Output: true
Explaination: If either a or b are palindromes the answer is true since you can split in the following way:
aprefix = "", asuffix = "x"
bprefix = "", bsuffix = "y"
Then, aprefix + bsuffix = "" + "y" = "y", which is a palindrome.

Example 2:

Input: a = "abdef", b = "fecab"
Output: true

Example 3:

Input: a = "ulacfd", b = "jizalu"
Output: true
Explaination: Split them at index 3:
aprefix = "ula", asuffix = "cfd"
bprefix = "jiz", bsuffix = "alu"
Then, aprefix + bsuffix = "ula" + "alu" = "ulaalu", which is a palindrome.

Example 4:

Input: a = "xbdef", b = "xecab"
Output: false

 

Constraints:

  • 1 <= a.length, b.length <= 105
  • a.length == b.length
  • a and b consist of lowercase English letters

Related Topics:
String

Solution 1.

// OJ: https://leetcode.com/problems/split-two-strings-to-make-palindrome/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
    bool check(string a, string b) {
        int N = a.size(), i = N / 2;
        while (i - 1 >= 0 && a[i - 1] == a[N - i]) --i; // a[i..(N-i-1)] is palindrome
        reverse(begin(b), end(b));
        return a.substr(0, i) == b.substr(0, i) || a.substr(N - i) == b.substr(N - i);
    }
public:
    bool checkPalindromeFormation(string a, string b) {
        return check(a, b) || check(b, a);
    }
};

Or don't create substring.

// OJ: https://leetcode.com/problems/split-two-strings-to-make-palindrome/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
    bool equal(string &a, string &b, int i) {
        while (i - 1 >= 0 && a[i - 1] == b[a.size() - i]) --i;
        return i == 0;
    }
    bool check(string &a, string &b) {
        int N = a.size(), i = N / 2;
        while (i - 1 >= 0 && a[i - 1] == a[N - i]) --i;
        return equal(a, b, i) || equal(b, a, i);
    }
public:
    bool checkPalindromeFormation(string a, string b) {
        return check(a, b) || check(b, a);
    }
};