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: