|
| 1 | +/** |
| 2 | + * 1616. Split Two Strings to Make Palindrome |
| 3 | + * https://leetcode.com/problems/split-two-strings-to-make-palindrome/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given two strings a and b of the same length. Choose an index and split both strings at |
| 7 | + * the same index, splitting a into two strings: aprefix and asuffix where a = aprefix + asuffix, |
| 8 | + * and splitting b into two strings: bprefix and bsuffix where b = bprefix + bsuffix. Check if |
| 9 | + * aprefix + bsuffix or bprefix + asuffix forms a palindrome. |
| 10 | + * |
| 11 | + * When you split a string s into sprefix and ssuffix, either ssuffix or sprefix is allowed to be |
| 12 | + * empty. For example, if s = "abc", then "" + "abc", "a" + "bc", "ab" + "c" , and "abc" + "" are |
| 13 | + * valid splits. |
| 14 | + * |
| 15 | + * Return true if it is possible to form a palindrome string, otherwise return false. |
| 16 | + * |
| 17 | + * Notice that x + y denotes the concatenation of strings x and y. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {string} a |
| 22 | + * @param {string} b |
| 23 | + * @return {boolean} |
| 24 | + */ |
| 25 | +var checkPalindromeFormation = function(a, b) { |
| 26 | + return check(a, b) || check(b, a); |
| 27 | + |
| 28 | + function isPalindrome(str, left, right) { |
| 29 | + while (left < right) { |
| 30 | + if (str[left++] !== str[right--]) return false; |
| 31 | + } |
| 32 | + return true; |
| 33 | + } |
| 34 | + |
| 35 | + function check(str1, str2) { |
| 36 | + let left = 0; |
| 37 | + let right = str1.length - 1; |
| 38 | + |
| 39 | + while (left < right && str1[left] === str2[right]) { |
| 40 | + left++; |
| 41 | + right--; |
| 42 | + } |
| 43 | + |
| 44 | + return isPalindrome(str1, left, right) || isPalindrome(str2, left, right); |
| 45 | + } |
| 46 | +}; |
0 commit comments