添加(0516.最长回文子序列.md):增加typescript版本

This commit is contained in:
Steve2020
2022-05-21 14:26:24 +08:00
parent e07a3caa02
commit 8e7663c9c6

View File

@ -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];
};
```
----------------------- -----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div> <div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>