058_回文子串
知识点:动态规划、回文
LeetCode第六百四十七题:https://leetcode-cn.com/problems/palindromic-substrings/solution/
还有个暴力解法,但是时间复杂度也为O(n2),与dp持平,就是:每个字符为中心进行扩散判断,也称中心扩散法。
语言:GoLang
// DP解法,时空均为O(n)
func countSubstrings(s string) int {
sLen := len(s)
count := 0
dp := [1010][1010]bool{}
for i := 0; i < sLen; i++ {
dp[i][i] = true
count++
if i < sLen - 1 && s[i] == s[i + 1] {
dp[i][i + 1] = true
count++
}
}
// 从len=3开始遍历
for length := 2; length < sLen; length++ {
for i := 0; i < sLen - length; i++ {
if s[i] == s[i + length] {
if dp[i + 1][i + length - 1] {
count++
dp[i][i + length] = true
}
} else {
dp[i][i + length] = false
}
}
}
return count
}
// 朴素解法,时间O(n^3),空间O(1)
func countSubstrings_(s string) int {
sLen := len(s)
count := 0
for i := 0; i < sLen; i++ {
for j := i + 1; j <= sLen; j++ {
if isPalindromic(s[i:j]) {
count++
}
}
}
return count
}
func isPalindromic(s string) bool {
sLen := len(s)
for i := 0; i < sLen / 2; i++ {
if s[i] != s[sLen - 1 - i] {
return false
}
}
return true
}