Longest Palindrome from Two Words
Problem statement
Given two lowercase strings word1 and word2, choose one nonempty subsequence from each string. Keep the original order of characters within each chosen subsequence, then concatenate the choice from word1 before the choice from word2.
Find the maximum possible length of a concatenation that is a palindrome. Return 0 if no such palindrome can use at least one character from both words. You may skip any characters in either word, but you may not reorder selected characters.
Function
maxPalindromeFromTwoWords(word1: String, word2: String) → intExamples
Example 1
word1 = "ab"word2 = "ba"return = 4Select both words to make abba.
Example 2
word1 = "abc"word2 = "def"return = 0No character in the first word matches one in the second, so a palindrome using both is impossible.
Example 3
word1 = "caa"word2 = "ac"return = 5Select every character to make caaac.
Example 4
word1 = "ab"word2 = "cba"return = 5Select every character to make abcba.
Constraints
1 <= word1.length, word2.length <= 500.- Both strings contain only lowercase English letters.
- The result is a length, not the palindrome text; any ties have the same answer.