代码随想录二刷Day57
今日任务
647.回文子串
516.最长回文子序列
语言:Go
647. 回文子串
链接:https://leetcode.cn/problems/palindromic-substrings/
func countSubstrings(s string) int {
//dp[i][j]表示s[i:j]是否为回文子串(左闭右闭)
//i <= j
dp := make([][]bool, len(s))
for i := 0; i < len(s); i++ {
dp[i] = make([]bool, len(s))
}
res := 0
for i := len(s) - 1; i >= 0; i-- {
for j := i; j < len(s); j++ {
if s[i] == s[j] {
if j - i <= 1 { //a, aa
dp[i][j] = true
res++
} else if dp[i + 1][j - 1] { //aaa
dp[i][j] = true
res++
}
}
}
}
return res
}
516. 最长回文子序列
链接:https://leetcode.cn/problems/longest-palindromic-subsequence/
func max(i, j int) int {
if i < j {
return j
} else {
return i
}
}
func longestPalindromeSubseq(s string) int {
//dp[i][j]表示s[i:j]最大回文子序列长度为dp[i][j](左闭右闭)
//i <= j
dp := make([][]int, len(s))
for i := 0; i < len(s); i++ {
dp[i] = make([]int, len(s))
}
for i := len(s) - 1; i >= 0; i-- {
for j := i; j < len(s); j++ {
if i == j {
dp[i][j] = 1
continue
}
if s[i] == s[j] {
dp[i][j] = dp[i + 1][j - 1] + 2
} else {
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
}
}
}
return dp[0][len(s) - 1]
}
/*
b b b a b
b 1 2 3 3 4
b 1 2 2 3
b 1 1 3
a 1 1
b 1
*/