647. 回文子串

image.png
暴力

  1. func countSubstrings(s string) int {
  2. var res int
  3. for i := 0; i < len(s); i++ {
  4. for j := i + 1; j <= len(s); j++ {
  5. if isPalindrome(s[i:j]) {
  6. res++
  7. }
  8. }
  9. }
  10. return res
  11. }
  12. func isPalindrome(s string) bool {
  13. l := 0
  14. r := len(s) - 1
  15. for l < r {
  16. if s[l] != s[r] {
  17. return false
  18. }
  19. l++
  20. r--
  21. }
  22. return true
  23. }

image.png

动态规划

  1. func countSubstrings(s string) int {
  2. var res int
  3. flag := make([][]bool,len(s))
  4. for i:=range flag{
  5. flag[i]= make([]bool,len(s))
  6. }
  7. for j := 0; j < len(s); j++ {
  8. for i := j ; i >=0; i-- {
  9. if s[i] == s[j] && (j - i < 2 || flag[i + 1][j - 1]) {
  10. flag[i][j] = true
  11. res++
  12. }
  13. }
  14. }
  15. return res
  16. }

abba
a
b
ba
b
bb
bba
a
ba
bba
abba

  1. func countSubstrings(s string) int {
  2. if len(s) <= 1 {
  3. return len(s)
  4. }
  5. sLen := len(s)
  6. palindrome := make([][]bool, sLen)
  7. for i := 0; i < len(palindrome); i++ {
  8. palindrome[i] = make([]bool, sLen)
  9. }
  10. count := sLen
  11. for i := sLen - 1; i >= 0; i-- {
  12. palindrome[i][i] = true
  13. for j := i + 1; j < sLen; j++ {
  14. if s[i] == s[j] {
  15. if j == i+1 {
  16. palindrome[i][j] = true
  17. } else {
  18. palindrome[i][j] = palindrome[i+1][j-1]
  19. }
  20. }
  21. if palindrome[i][j] {
  22. count++
  23. }
  24. }
  25. }
  26. return count
  27. }