From 08e390cb7e85eafbfcc69bb6d708a1fb7ffde50a Mon Sep 17 00:00:00 2001 From: Qi Jia <13632059+jackeyjia@users.noreply.github.com> Date: Sat, 17 Jul 2021 13:27:54 -0700 Subject: [PATCH] add js solution for countSubstrings --- problems/0647.回文子串.md | 44 +++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/problems/0647.回文子串.md b/problems/0647.回文子串.md index 31734bbc..d3b734ae 100644 --- a/problems/0647.回文子串.md +++ b/problems/0647.回文子串.md @@ -361,7 +361,51 @@ func countSubstrings(s string) int { } ``` +Javascript +> 动态规划 +```javascript +const countSubstrings = (s) => { + const strLen = s.length; + let numOfPalindromicStr = 0; + let dp = Array.from(Array(strLen), () => Array(strLen).fill(false)); + for(let j = 0; j < strLen; j++) { + for(let i = 0; i <= j; i++) { + if(s[i] === s[j]) { + if((j - i) < 2) { + dp[i][j] = true; + } else { + dp[i][j] = dp[i+1][j-1]; + } + numOfPalindromicStr += dp[i][j] ? 1 : 0; + } + } + } + + return numOfPalindromicStr; +} +``` + +> 双指针法: +```javascript +const countSubstrings = (s) => { + const strLen = s.length; + let numOfPalindromicStr = 0; + + for(let i = 0; i < 2 * strLen - 1; i++) { + let left = Math.floor(i/2); + let right = left + i % 2; + + while(left >= 0 && right < strLen && s[left] === s[right]){ + numOfPalindromicStr++; + left--; + right++; + } + } + + return numOfPalindromicStr; +} +``` -----------------------