From 80dda7ac0918d857d969a27f278e882886ec98f8 Mon Sep 17 00:00:00 2001 From: Qi Jia <13632059+jackeyjia@users.noreply.github.com> Date: Sat, 17 Jul 2021 14:37:00 -0700 Subject: [PATCH] add js solution for longestPalindromeSubseq --- problems/0516.最长回文子序列.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/problems/0516.最长回文子序列.md b/problems/0516.最长回文子序列.md index a4f0522f..388d8d6a 100644 --- a/problems/0516.最长回文子序列.md +++ b/problems/0516.最长回文子序列.md @@ -214,7 +214,29 @@ func longestPalindromeSubseq(s string) int { } ``` +Javascript: +```javascript +const longestPalindromeSubseq = (s) => { + const strLen = s.length; + let dp = Array.from(Array(strLen), () => Array(strLen).fill(0)); + + for(let i = 0; i < strLen; i++) { + dp[i][i] = 1; + } + for(let i = strLen - 1; i >= 0; i--) { + for(let j = i + 1; j < strLen; j++) { + if(s[i] === s[j]) { + 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][strLen - 1]; +}; +``` -----------------------