• Time:O(n)
• Space:O(1)

## C++

``````class Solution {
public:
int countBinarySubstrings(string s) {
int ans = 0;
int prevEquals = 0;
int currEquals = 1;

for (int i = 0; i + 1 < s.length(); ++i)
if (s[i] == s[i + 1])
++currEquals;
else {
ans += min(prevEquals, currEquals);
prevEquals = currEquals;
currEquals = 1;
}

return ans + min(prevEquals, currEquals);
}
};
``````

## JAVA

``````class Solution {
public int countBinarySubstrings(String s) {
int ans = 0;
int prevEquals = 0;
int currEquals = 1;

for (int i = 0; i + 1 < s.length(); ++i)
if (s.charAt(i) == s.charAt(i + 1))
++currEquals;
else {
ans += Math.min(prevEquals, currEquals);
prevEquals = currEquals;
currEquals = 1;
}

return ans + Math.min(prevEquals, currEquals);
}
}
``````

## Python

``````class Solution:
def countBinarySubstrings(self, s: str) -> int:
ans = 0
prevCount = 0
equals = 1

for i in range(len(s) - 1):
if s[i] == s[i + 1]:
equals += 1
else:
ans += min(prevCount, equals)
prevCount = equals
equals = 1

return ans + min(prevCount, equals)
``````