forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestPalindromicSubsequence.js
More file actions
Latest commit
33 lines (26 loc) · 779 Bytes
/
Copy pathLongestPalindromicSubsequence.js
File metadata and controls
33 lines (26 loc) · 779 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/*
LeetCode -> https://leetcode.com/problems/longest-palindromic-subsequence/
Given a string s, find the longest palindromic subsequence's length in s.
You may assume that the maximum length of s is 1000.
*/
exportconstlongestPalindromeSubsequence=function(s){
constn=s.length
constdp=newArray(n)
.fill(0)
.map((item)=>newArray(n).fill(0).map((item)=>0))
// fill predefined for single character
for(leti=0;i<n;i++){
dp[i][i]=1
}
for(leti=1;i<n;i++){
for(letj=0;j<n-i;j++){
constcol=j+i
if(s[j]===s[col]){
dp[j][col]=2+dp[j+1][col-1]
}else{
dp[j][col]=Math.max(dp[j][col-1],dp[j+1][col])
}
}
}
returndp[0][n-1]
}