Skip to content

Commit 1483f83

Browse files
authored
Create 516-longest-palindromic-subsequence.js
1 parent db04cef commit 1483f83

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
* @param {string} s
3+
* @return {number}
4+
*/
5+
const longestPalindromeSubseq = function(s) {
6+
const len = s.length
7+
const dp = Array.from({length: len + 1}, () => new Array(len + 1).fill(0))
8+
for(let i = len - 1; i >= 0; i--) {
9+
dp[i][i] = 1
10+
for(let j = i + 1; j < len; j++) {
11+
if(s[i] === s[j]) {
12+
dp[i][j] = dp[i+1][j-1] + 2
13+
} else {
14+
dp[i][j] = Math.max(dp[i][j - 1], dp[i+1][j])
15+
}
16+
}
17+
}
18+
return dp[0][s.length - 1]
19+
};

0 commit comments

Comments
 (0)