696.count-binary-substrings.go 327 B

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