Beautiful Binary String

Sort by

recency

|

847 Discussions

|

  • + 0 comments

    Here are my c++ solution, explanation here : https://youtu.be/xf0JsPRH5rs

    Solution 1 :

    int beautifulBinaryString(string b) {
        int ans = 0;
        for(int i = 0; i < b.size();){
            string sub = b.substr(i, 3);
            if(sub == "010") {
                ans++;
                i+=3;
            }else i++;
        }
        return ans;
    }
    

    Solution 2 :

    int beautifulBinaryString(string b) {
        regex re("010");
        string c = regex_replace(b, re, "");
        return (b.size() - c.size()) / 3;
    }
    
  • + 0 comments
    def beautifulBinaryString(b):
        m=0
        while '010' in b:
            for i in range(len(b)-2):
                if b[i]=='0' and b[i+1]=='1' and b[i+2]=='0':
                    m+=1
                    b=b[i+3:]
                    break
        return m
    
  • + 1 comment

    PYTHON SOLUTION

    def beautifulBinaryString(b):
        # Write your code here
        return len(b.split('010'))-1
    
  • + 0 comments

    python3

    def beautifulBinaryString(b):
        # Write your code here
    
        count = 0   
        while b.find('010') != -1:
           b = b.replace('010', '011', 1)
           count +=1
        
        return count
    
  • + 0 comments

    Perl:

    sub beautifulBinaryString {
        my $b = shift;
        my $cnt = 0;
    
        while ($b =~ m/010/) {
            $b =~ s/010/011/;
            $cnt++;
        }
        return $cnt;
    }