From 9b3853eae2761011f82b77aa45b840482e1b472b Mon Sep 17 00:00:00 2001 From: Baturu <45113401+z80160280@users.noreply.github.com> Date: Tue, 8 Jun 2021 21:05:11 -0700 Subject: [PATCH] =?UTF-8?q?Update=200647.=E5=9B=9E=E6=96=87=E5=AD=90?= =?UTF-8?q?=E4=B8=B2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0647.回文子串.md | 50 +++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/problems/0647.回文子串.md b/problems/0647.回文子串.md index 58949571..31734bbc 100644 --- a/problems/0647.回文子串.md +++ b/problems/0647.回文子串.md @@ -284,6 +284,56 @@ class Solution { Python: +> 动态规划: +```python +class Solution: + def countSubstrings(self, s: str) -> int: + dp = [[False] * len(s) for _ in range(len(s))] + result = 0 + for i in range(len(s)-1, -1, -1): #注意遍历顺序 + for j in range(i, len(s)): + if s[i] == s[j]: + if j - i <= 1: #情况一 和 情况二 + result += 1 + dp[i][j] = True + elif dp[i+1][j-1]: #情况三 + result += 1 + dp[i][j] = True + return result +``` + +> 动态规划:简洁版 +```python +class Solution: + def countSubstrings(self, s: str) -> int: + dp = [[False] * len(s) for _ in range(len(s))] + result = 0 + for i in range(len(s)-1, -1, -1): #注意遍历顺序 + for j in range(i, len(s)): + if s[i] == s[j] and (j - i <= 1 or dp[i+1][j-1]): + result += 1 + dp[i][j] = True + return result +``` + +> 双指针法: +```python +class Solution: + def countSubstrings(self, s: str) -> int: + result = 0 + for i in range(len(s)): + result += self.extend(s, i, i, len(s)) #以i为中心 + result += self.extend(s, i, i+1, len(s)) #以i和i+1为中心 + return result + + def extend(self, s, i, j, n): + res = 0 + while i >= 0 and j < n and s[i] == s[j]: + i -= 1 + j += 1 + res += 1 + return res +``` Go: ```Go