C++ easy understanding solution


  • 6
    B
    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[i-1]){
                    ++count;
                }else{
                    rec.push_back(count);
                    count = 1;
                }
            }
            int res = 0;
            for(int i=1, n=rec.size(); i<n; ++i){
                res += min(rec[i-1], rec[i]);
            }
            return res;
        }
    };
    

  • 0

    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()?


  • 0
    B

    @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[i-1]){
                    ++count;
                }else{
                    rec.push_back(count);
                    count = 1;
                }
            }
    

  • 0
    P

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


  • 0
    Y

    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;
    }
    };
    '''


Log in to reply
 

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