一、题目描述

二、解题思路

找每次连续的1或者0的个数,存入vector,之后每次选取紧邻着的两个中较小的那个相加给res
比如:100011111001110,得到vector = {1, 3, 5, 2, 3, 1},所以res = 1 + 3 + 2 + 2 + 1

三、解题代码

class Solution {
   
public:
    int countBinarySubstrings(string s) {
   
        int l = 0, r = 0;
        int a[2];
        int cur = -1;
        int res = 0;
        for(; l < s.size() && r < s.size(); ){
   
            auto tmp = s[l];
            for(r = l; r < s.size() && s[r] == tmp; r++);
            a[++cur % 2] = r - l;
            l = r;
            if(cur >= 1)    res += min(a[0], a[1]);
        }
        return res;
    }
};

四、运行结果