Skip to content

Commit 2107cfd

Browse files
committed
Add solution #516
1 parent 9158beb commit 2107cfd

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -412,6 +412,7 @@
412412
513|[Find Bottom Left Tree Value](./0513-find-bottom-left-tree-value.js)|Medium|
413413
514|[Freedom Trail](./0514-freedom-trail.js)|Hard|
414414
515|[Find Largest Value in Each Tree Row](./0515-find-largest-value-in-each-tree-row.js)|Medium|
415+
516|[Longest Palindromic Subsequence](./0516-longest-palindromic-subsequence.js)|Medium|
415416
520|[Detect Capital](./0520-detect-capital.js)|Easy|
416417
521|[Longest Uncommon Subsequence I](./0521-longest-uncommon-subsequence-i.js)|Easy|
417418
530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* 516. Longest Palindromic Subsequence
3+
* https://leetcode.com/problems/longest-palindromic-subsequence/
4+
* Difficulty: Medium
5+
*
6+
* Given a string s, find the longest palindromic subsequence's length in s.
7+
*
8+
* A subsequence is a sequence that can be derived from another sequence by deleting some
9+
* or no elements without changing the order of the remaining elements.
10+
*/
11+
12+
/**
13+
* @param {string} s
14+
* @return {number}
15+
*/
16+
/**
17+
* @param {string} s
18+
* @return {number}
19+
*/
20+
var longestPalindromeSubseq = function(s) {
21+
const dp = new Array(s.length).fill(0);
22+
23+
for (let i = s.length - 1, previous; i >= 0; i--) {
24+
previous = dp.slice();
25+
dp[i] = 1;
26+
for (let j = i + 1; j < s.length; j++) {
27+
if (s[i] === s[j]) {
28+
dp[j] = (previous[j - 1] || 0) + 2;
29+
} else {
30+
dp[j] = Math.max(dp[j - 1], previous[j]);
31+
}
32+
}
33+
}
34+
35+
return dp[s.length - 1];
36+
};

0 commit comments

Comments
 (0)