Maximize Palindrome Length From Subsequences LeetCode solution in Java

1
class Solution {
2
public int longestPalindrome(String word1, String word2) {
3
String lWord = word1 + word2;
4
return palindrome(
5
lWord,
6
0,
7
lWord.length() - 1,
8
word1.length(),
9
false,
10
new int[lWord.length()][lWord.length()][2]);
11
}
12

13
private int palindrome(
14
String word, int start, int end, int boundary, boolean isFound, int[][][] dp) {
15
if ((!isFound && (start >= boundary || end < boundary)) || (start > end)) return 0;
16

17
if (dp[start][end][isFound ? 0 : 1] != 0) return dp[start][end][isFound ? 0 : 1];
18

19
return dp[start][end][isFound ? 0 : 1] =
20
word.charAt(start) == word.charAt(end)
21
? ((start == end ? 1 : 2) + palindrome(word, start + 1, end - 1, boundary, true, dp))
22
: Math.max(
23
palindrome(word, start + 1, end, boundary, isFound, dp),
24
palindrome(word, start, end - 1, boundary, isFound, dp));
25
}
26
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0