Beautiful Binary String

Sort by

recency

|

849 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

    My Java solution:

     public static int beautifulBinaryString(String b) {
            //goal: determine min removals to a string not have 010
            int min = 0;
            for (int i = 0; i < b.length() - 2; i++) {
                if (b.substring(i, i + 3).equals("010")) {
                    min++;
                    i += 2; // Skip next two characters to avoid overlapping patterns
                }
            }
            return min;
        }
    
  • + 0 comments

    c++

    int beautifulBinaryString(string b) {
        int val =0;
        int n = b.size();
        for (int i=2; i< n; i++) {
            if (b.at(i) == '0' and b.at(i-2)=='0' and b.at(i-1)=='1') {
                b.at(i) = '1';
                val++;
            }
        }
        return val;
    }
    
  • + 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
    
  • + 3 comments

    PYTHON SOLUTION

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