Skip to content

Commit 44afa53

Browse files
committed
Added Longest Plaindromic subsequence
1 parent 129323d commit 44afa53

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
LeetCode -> https://leetcode.com/problems/longest-palindromic-subsequence/
3+
4+
Given a string s, find the longest palindromic subsequence's length in s.
5+
You may assume that the maximum length of s is 1000.
6+
7+
*/
8+
9+
const longestPalindromeSubsequence = function (s) {
10+
const n = s.length
11+
12+
const dp = new Array(n).fill(0).map(item => new Array(n).fill(0).map(item => 0))
13+
14+
// fill predefined for single character
15+
for (let i = 0; i < n; i++) {
16+
dp[i][i] = 1
17+
}
18+
19+
for (let i = 1; i < n; i++) {
20+
for (let j = 0; j < n - i; j++) {
21+
const col = j + i
22+
if (s[j] == s[col]) {
23+
dp[j][col] = 2 + dp[j + 1][col - 1]
24+
} else {
25+
dp[j][col] = Math.max(dp[j][col - 1], dp[j + 1][col])
26+
}
27+
}
28+
}
29+
30+
return dp[0][n - 1]
31+
}
32+
33+
const main = () => {
34+
console.log(longestPalindromeSubsequence('bbbab')) // 4
35+
console.log(longestPalindromeSubsequence('axbya')) // 3
36+
console.log(longestPalindromeSubsequence('racexyzcxar')) // 7
37+
}
38+
39+
main()

0 commit comments

Comments
 (0)