LeetCode 1616. Split Two Strings to Make Palindrome

Question

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.

Constraints:

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

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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.

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

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.

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

Solution

题目意思比较明确,即我们找一个相同的位置分割a,b字符串,然后看a的前部分和b的后半部分或者b的前半部分和a的后半部分组成的字符串是否为回文字符串。所以,我们可以简单的遍历每一个位置然后分别分割然后组成字符串,之后再验证是否符合回文的特性,但是这样子就是N^2的算法。这样的算法会TLE,所以我们需要更加高效的方式,由于我们都是用前半部分或者是后半部分合成,我们可以看例子3,a = "ulacfd", b = "jizalu",我们其实可以得到最长的a前缀子串以及b最长的后缀子串,即ulaalu,然后再验证中间剩下的部分,如果符合条件,即符合。具体可以看看Huahua的视频

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.leetcode.string.Palindrome;

/**
* @Date: 10/14/2020
* @Description: greedy
**/
public class _1616_Split_Two_Strings_to_Make_Palindrome {
public boolean checkPalindromeFormation(String a, String b) {
// 找最长的前后缀匹配。
// 相当于可以看a,b两个字符串prefix 以及suffix匹配最长的palindrome
return check(a, b) || check(b, a);
}


public boolean check(String a, String b) {
int i = 0, j = b.length() - 1;
while (i < a.length() && j >= 0 &&
a.charAt(i) == b.charAt(j)) {
i++;
j--;
}
return isValid(a, i, j) || isValid(b, i, j);
}

public boolean isValid(String s, int i, int j) {
while (i < j) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
}

Reference