Skip to content

Commit 8f942dd

Browse files
authored
Create 1771-maximize-palindrome-length-from-subsequences.js
1 parent d229762 commit 8f942dd

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @param {string} word1
3+
* @param {string} word2
4+
* @return {number}
5+
*/
6+
const longestPalindrome = function(word1, word2) {
7+
const sz = word1.length + word2.length
8+
let res = 0;
9+
const dp = Array.from({ length: sz + 1 }, () => Array(sz + 1).fill(0))
10+
longestPalindromeSubseq(word1 + word2, dp);
11+
for (let i = 0; i < word1.length; ++i)
12+
for (let j = word2.length - 1; j >= 0; --j)
13+
if (word1[i] == word2[j]) {
14+
res = Math.max(res, dp[i][word1.length + j + 1]);
15+
break;
16+
}
17+
return res;
18+
19+
}
20+
function longestPalindromeSubseq( s, dp) {
21+
for (let len = 1; len <= s.length; ++len)
22+
for (let i = 0; i + len <= s.length; ++i)
23+
dp[i][i + len] = s[i] == s[i + len - 1] ?
24+
dp[i + 1][i + len - 1] + (len == 1 ? 1 : 2) :
25+
Math.max(dp[i][i + len - 1], dp[i + 1][i + len]);
26+
return dp[0][s.length];
27+
}
28+
29+

0 commit comments

Comments
 (0)