C++ O(n) time O(1) space concise solution


  • 0
    G
    int countBinarySubstrings(string s) {
        int sub0 = 0;
        int sub1 = 0;
        int count = 0;
        char stat = *s.begin();
        for(auto i=s.begin(); i!=s.end(); i++){
            if(*i == '0' && stat == '0'){
                sub0++;
                if(sub0 <= sub1) count++;
            }else if(*i == '1' && stat == '1'){
                sub1++;
                if(sub1 <= sub0) count++;
            }else if(*i == '0' && stat == '1'){
                sub0 = 1;
                stat = '0';
                if(sub0 <= sub1) count++;
            }else if(*i == '1' && stat == '0'){
                sub1 = 1;
                stat = '1';
                if(sub1 <= sub0) count++;
            }
        }
        return count;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.