From 8e7663c9c663db8c7d24aa1528d45c68fe6f5e29 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sat, 21 May 2022 14:26:24 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880516.=E6=9C=80?= =?UTF-8?q?=E9=95=BF=E5=9B=9E=E6=96=87=E5=AD=90=E5=BA=8F=E5=88=97.md?= =?UTF-8?q?=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0516.最长回文子序列.md | 29 ++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/problems/0516.最长回文子序列.md b/problems/0516.最长回文子序列.md index 69536cef..1b0ee9a3 100644 --- a/problems/0516.最长回文子序列.md +++ b/problems/0516.最长回文子序列.md @@ -236,6 +236,35 @@ const longestPalindromeSubseq = (s) => { }; ``` +TypeScript: + +```typescript +function longestPalindromeSubseq(s: string): number { + /** + dp[i][j]:[i,j]区间内,最长回文子序列的长度 + */ + const length: number = s.length; + const dp: number[][] = new Array(length).fill(0) + .map(_ => new Array(length).fill(0)); + for (let i = 0; i < length; i++) { + dp[i][i] = 1; + } + // 自下而上,自左往右遍历 + for (let i = length - 1; i >= 0; i--) { + for (let j = i + 1; j < length; j++) { + if (s[i] === s[j]) { + dp[i][j] = dp[i + 1][j - 1] + 2; + } else { + dp[i][j] = Math.max(dp[i][j - 1], dp[i + 1][j]); + } + } + } + return dp[0][length - 1]; +}; +``` + + + -----------------------