From f6501464cfdfe0c207e5f1026b1b3251d9b5c927 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sat, 21 May 2022 11:48:18 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880647.=E5=9B=9E?= =?UTF-8?q?=E6=96=87=E5=AD=90=E4=B8=B2.md=EF=BC=89=EF=BC=9A=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0647.回文子串.md | 57 +++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/problems/0647.回文子串.md b/problems/0647.回文子串.md index 913aec65..6045ba7b 100644 --- a/problems/0647.回文子串.md +++ b/problems/0647.回文子串.md @@ -406,6 +406,63 @@ const countSubstrings = (s) => { } ``` +TypeScript: + +> 动态规划: + +```typescript +function countSubstrings(s: string): number { + /** + dp[i][j]: [i,j]区间内的字符串是否为回文(左闭右闭) + */ + const length: number = s.length; + const dp: boolean[][] = new Array(length).fill(0) + .map(_ => new Array(length).fill(false)); + let resCount: number = 0; + // 自下而上,自左向右遍历 + for (let i = length - 1; i >= 0; i--) { + for (let j = i; j < length; j++) { + if ( + s[i] === s[j] && + (j - i <= 1 || dp[i + 1][j - 1] === true) + ) { + dp[i][j] = true; + resCount++; + } + } + } + return resCount; +}; +``` + +> 双指针法: + +```typescript +function countSubstrings(s: string): number { + const length: number = s.length; + let resCount: number = 0; + for (let i = 0; i < length; i++) { + resCount += expandRange(s, i, i); + resCount += expandRange(s, i, i + 1); + } + return resCount; +}; +function expandRange(s: string, left: number, right: number): number { + let palindromeNum: number = 0; + while ( + left >= 0 && right < s.length && + s[left] === s[right] + ) { + palindromeNum++; + left--; + right++; + } + return palindromeNum; +} +``` + + + -----------------------