Beautiful Binary String

Sort by

recency

|

839 Discussions

|

  • + 0 comments

    Simple C Solution

    int beautifulBinaryString(char* b) {
        int count = 0;
        int length = strlen(b);
        
        for (int i = 0; i <= length - 3; i++) {
            // Check for the substring "010"
            if (b[i] == '0' && b[i + 1] == '1' && b[i + 2] == '0') {
                count++;
                // Skip the next two characters to avoid overlapping
                i += 2; 
            }
        }
        
        return count;
    }
    
  • + 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

    SIMPLEST SOLUTION IN PYTHON-

    l=b.split('010')

    return len(l)-1

  • + 0 comments

    Python solution without any tricks :-

    def beautifulBinaryString(b):
        num = 0
        while len(b)>=3:
            if b[:3] == '010':
                num += 1
                b = b[3:]
            else:
               b = b[1:]
        return num
    
  • + 0 comments
    def beautifulBinaryString(b):
        return b.count("010")