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
andb
consist of lowercase English letters
Example
1 | Input: a = "x", b = "y" |
Solution
题目意思比较明确,即我们找一个相同的位置分割a,b字符串,然后看a的前部分和b的后半部分或者b的前半部分和a的后半部分组成的字符串是否为回文字符串。所以,我们可以简单的遍历每一个位置然后分别分割然后组成字符串,之后再验证是否符合回文的特性,但是这样子就是N^2
的算法。这样的算法会TLE,所以我们需要更加高效的方式,由于我们都是用前半部分或者是后半部分合成,我们可以看例子3,a = "ulacfd", b = "jizalu"
,我们其实可以得到最长的a前缀子串以及b最长的后缀子串,即ula
和alu
,然后再验证中间剩下的部分,如果符合条件,即符合。具体可以看看Huahua的视频
Code
1 | package com.leetcode.string.Palindrome; |