I count the consecutive 1’s and 0’s, and for each transition, we take the minimum number of 1’s and 0’s, and this is the number of words that can be formed in this transtiion.

Code

class Solution {
public:
    int countBinarySubstrings(string s) {
        int n = s.size();
        vector<int> cnt;
        cnt.reserve(n);

        int zero = 0;
        int one = 0;
        for(int i = 0 ; i < n ; ++i) {
            if(s[i] == '1') {
                if(zero != 0) {
                    cnt.push_back(zero);
                    zero = 0;
                }
                ++one;
            } else {
                if(one != 0) {
                    cnt.push_back(one);
                    one = 0;
                }
                ++zero;
            }
        }
        if(zero != 0) cnt.push_back(zero);
        if(one != 0) cnt.push_back(one);

        int m = cnt.size();
        int totalCnt = 0;
        for(int i = 1 ; i < m ; ++i) {
            totalCnt += min(cnt[i-1], cnt[i]);
        }

        return totalCnt;
    }
};