From f5fc6baddca9af176b77648229ae26fd4bae137e Mon Sep 17 00:00:00 2001 From: meifannao Date: Sun, 25 Feb 2024 22:12:35 +0800 Subject: [PATCH] =?UTF-8?q?0647.=E5=9B=9E=E6=96=87=E5=AD=90=E4=B8=B2?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0Golang=E7=9A=84=E5=8F=8C=E6=8C=87=E9=92=88?= =?UTF-8?q?=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0647.回文子串.md | 42 +++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/problems/0647.回文子串.md b/problems/0647.回文子串.md index d94d18c5..4887ff83 100644 --- a/problems/0647.回文子串.md +++ b/problems/0647.回文子串.md @@ -397,6 +397,7 @@ class Solution: ``` ### Go: +> 动态规划: ```Go func countSubstrings(s string) int { @@ -422,6 +423,47 @@ func countSubstrings(s string) int { return res } ``` +> 动态规划:简洁版 +```Go +func countSubstrings(s string) int { + res := 0 + dp := make([][]bool, len(s)) + for i := 0; i < len(s); i++ { + dp[i] = make([]bool, len(s)) + } + + for i := len(s) - 1; i >= 0; i-- { + for j := i; j < len(s); j++ { + if s[i] == s[j] && (j-i <= 1 || dp[i+1][j-1]) { + res++ + dp[i][j] = true + } + } + } + return res +} +``` + +> 双指针法: +```Go +func countSubstrings(s string) int { + extend := func(i, j int) int { + res := 0 + for i >= 0 && j < len(s) && s[i] == s[j] { + i -- + j ++ + res ++ + } + return res + } + res := 0 + for i := 0; i < len(s); i++ { + res += extend(i, i) // 以i为中心 + res += extend(i, i+1) // 以i和i+1为中心 + } + return res +} +``` ### Javascript: