diff --git a/README.md b/README.md index 98945674..9960b26b 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,8 @@ Step 2. Add the dependency 展开查看 +https://leetcode-cn.com/problems/longest-palindromic-subsequence/ + https://leetcode.cn/problems/minimum-number-of-operations-to-reinitialize-a-permutation/ https://leetcode.cn/problems/palindromic-substrings/ diff --git a/longest-palindromic-subsequence/index.ts b/longest-palindromic-subsequence/index.ts new file mode 100644 index 00000000..99601316 --- /dev/null +++ b/longest-palindromic-subsequence/index.ts @@ -0,0 +1,19 @@ +function longestPalindromeSubseq(s: string): number { + const n = s.length; + const dp: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(0)); + for (let i = n - 1; i >= 0; i--) { + dp[i][i] = 1; + const c1 = s[i]; + for (let j = i + 1; j < n; j++) { + const c2 = s[j]; + if (c1 === c2) { + dp[i][j] = dp[i + 1][j - 1] + 2; + } else { + dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]); + } + } + } + return dp[0][n - 1]; +} + +export default longestPalindromeSubseq;