647.palindromic-substrings.go 350 B

123456789101112131415161718192021222324
  1. func countSubstrings(s string) int {
  2. n, cnt := len(s), 0
  3. if n == 0 {
  4. return cnt
  5. }
  6. for i := range s {
  7. cnt++
  8. for j := 1; 0 <= i-j && i+j < n; j++ {
  9. if s[i-j] == s[i+j] {
  10. cnt++
  11. } else {
  12. break
  13. }
  14. }
  15. for j := 1; 0 <= i-j+1 && i+j < n; j++ {
  16. if s[i-j+1] == s[i+j] {
  17. cnt++
  18. } else {
  19. break
  20. }
  21. }
  22. }
  23. return cnt
  24. }