Beautiful Binary String

Sort by

recency

|

846 Discussions

|

  • + 0 comments

    PYTHON SOLUTION

    def beautifulBinaryString(b):
        # Write your code here
        return len(b.split('010'))-1
    
  • + 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

    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;
    }
    
  • + 0 comments

    My answer with Typescript, simple

    function beautifulBinaryString(b: string): number {
        /**
         * replace and counting until [b] doesn't include '010' any more
         */
        let count = 0
    
        while (b.includes('010')) {
            b = b.replace('010', '011')
            count++
        }
    
        return count;
    }