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 trueif it is possible to forma palindrome string, otherwise returnfalse.
Notice that x + y denotes the concatenation of strings x and y.
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:
1
2
3
4
Input:
a = "xbdef", b = "xecab"
Output:
false
Example 3:
1
2
3
4
5
6
7
8
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.
To form a palindrome by splitting at some index, we can try to match the prefix of one string with the suffix of the other. If a mismatch occurs, check if the remaining substring in either string is a palindrome. If so, the answer is true.
classSolution {
privatebooleanisPalindrome(String s, int l, int r) {
while (l < r) if (s.charAt(l++) != s.charAt(r--)) returnfalse;
returntrue;
}
privatebooleancheck(String a, String b) {
int l = 0, r = a.length() - 1;
while (l < r && a.charAt(l) == b.charAt(r)) {
l++;
r--;
}
return isPalindrome(a, l, r) || isPalindrome(b, l, r);
}
publicbooleancheckPalindromeFormation(String a, String b) {
return check(a, b) || check(b, a);
}
}
classSolution {
funcheckPalindromeFormation(a: String, b: String): Boolean {
funisPalindrome(s: String, l: Int, r: Int): Boolean {
var i = l
var j = r
while (i < j) {
if (s[i] != s[j]) returnfalse i++ j-- }
returntrue }
funcheck(a: String, b: String): Boolean {
var l = 0var r = a.length - 1while (l < r && a[l] == b[r]) {
l++ r-- }
return isPalindrome(a, l, r) || isPalindrome(b, l, r)
}
return check(a, b) || check(b, a)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
defcheckPalindromeFormation(self, a: str, b: str) -> bool:
defis_pal(s: str, l: int, r: int) -> bool:
while l < r:
if s[l] != s[r]:
returnFalse l +=1 r -=1returnTruedefcheck(a: str, b: str) -> bool:
l, r =0, len(a) -1while l < r and a[l] == b[r]:
l +=1 r -=1return is_pal(a, l, r) or is_pal(b, l, r)
return check(a, b) or check(b, a)