class Solution {
public:
int countBinarySubstrings(string s) {
vector<int> rec;
int count = 1;
for(int i=1, n=s.size(); i<=n; ++i){
if(s[i] == s[i1]){
++count;
}else{
rec.push_back(count);
count = 1;
}
}
int res = 0;
for(int i=1, n=rec.size(); i<n; ++i){
res += min(rec[i1], rec[i]);
}
return res;
}
};
C++ easy understanding solution


Hi @BADWOLF thanks for sharing your solution. Is it safe to assume that the C++ string ends in a null terminating character
\0
? Or would it be better to iterate through s.c_str()?

@claytonjwong Hi,thanks for pointing out my mistake.It is safer to iterate through s.c_str().Or I should modify the conditions in the loop as follows
for(int i=1, n=s.size(); i<=n; ++i){ if(i<n && s[i] == s[i1]){ ++count; }else{ rec.push_back(count); count = 1; } }

According to cppreference, If pos == size(), a reference to the character with value CharT() (the null character) is returned.

i think my solution is the clearest one
'''
class Solution {
public:
int countBinarySubstrings(string s) {
int count(0), nextn(0), pren(0);
for(int i=0; i<s.size(); ++i)
{
nextn = 1;
while(i+1<s.size() && s[i]==s[i+1]){++nextn; ++i;}
count += min(pren, nextn);
pren = nextn;
}
return count;
}
};
'''