Article Directory
1. Title
Give you two strings a and b, they are the same length.
Please select a subscript and separate the two strings at the same subscript.
Two strings can be obtained from a:, aprefix 和 asuffix
satisfies a = aprefix + asuffix
, and similarly, two strings are obtained from b bprefix 和 bsuffix
, satisfies b = bprefix + bsuffix
.
Please determine aprefix + bsuffix 或者 bprefix + asuffix
whether constitute a palindrome string.
When you split a string s into sprefix and ssuffix, ssuffix or sprefix can be empty.
Let's say, s = "abc"
then "" + "abc"
, "a" + "bc"
, "ab" + "c"
and "abc" + ""
are legal division.
If it can form a palindrome string, please return true, otherwise return false.
Please note that x + y means concatenating the strings x and y.
示例 1:
输入:a = "x", b = "y"
输出:true
解释:如果 a 或者 b 是回文串,那么答案一定为 true ,因为你可以如下分割:
aprefix = "", asuffix = "x"
bprefix = "", bsuffix = "y"
那么 aprefix + bsuffix = "" + "y" = "y" 是回文串。
示例 2:
输入:a = "ulacfd", b = "jizalu"
输出:true
解释:在下标为 3 处分割:
aprefix = "ula", asuffix = "cfd"
bprefix = "jiz", bsuffix = "alu"
那么 aprefix + bsuffix = "ula" + "alu" = "ulaalu" 是回文串。
提示:
1 <= a.length, b.length <= 105
a.length == b.length
a 和 b 都只包含小写英文字母
Source: LeetCode
Link: https://leetcode-cn.com/problems/split-two-strings-to-make-palindrome The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
2. Problem solving
class Solution {
public:
bool checkPalindromeFormation(string a, string b) {
int l = 0, r = a.size()-1;
while(l < r && a[l] == b[r])//先找出a的前缀 和 b的后缀的逆序 相同的
{
l++, r--;
}
if(ispalind(a.substr(l, r-l+1)) || ispalind(b.substr(l, r-l+1)))
return true;
l = 0, r = a.size()-1;
while(l < r && b[l] == a[r])// 找出b的前缀 和 a的后缀的逆序 相同的
{
l++, r--;
}
if(ispalind(a.substr(l, r-l+1)) || ispalind(b.substr(l, r-l+1)))
return true;
return false;
}
bool ispalind(string s)
{
int l = 0, r = s.size()-1;
while(l < r)
{
if(s[l++] != s[r--])
return false;
}
return true;
}
};
256 ms 28.4 MB
My CSDN blog address https://michael.blog.csdn.net/
Long press or scan the code to follow my official account (Michael Amin), cheer together, learn and progress together!