Beautiful Binary String

Sort by

recency

|

856 Discussions

|

  • + 0 comments
    # Beautiful Binary String
    def beautiful_binary_string(b):
        return b.count('101')
    
  • + 0 comments

    🧠 Problem: Beautiful Binary String

    This function counts the minimum number of operations required to make a binary string "beautiful" by replacing occurrences of '010' with '011'.

    def beautifulBinaryString(b):
        count = 0
        ans = 0
        while count != 1:
            a = b.find('010')
            if a >= 0:
                b = b[:a+2] + '1' + b[a+3:]
                ans += 1
                count += 0
            else:
                count += 1
        return ans
    

    🧪 Example Usage

    s = '0101010'
    print(beautifulBinaryString(s))  # Output: 2
    

    ✅ Notes:

    • The find('010') method locates the first occurrence of the pattern.
    • The string is modified to break the pattern by changing the last '0' to '1'.
    • The loop continues until no '010' is found.
  • + 0 comments

    // c#

    public static int beautifulBinaryString(string b)
    {       
        string newB = b.Replace("010", "xxx");
        int occur = 0;
    
        for(int i=0; i<newB.Length; i++)
        {
            if (newB.Substring(i,1) == "x")
            {
                i += 2;
                occur++;
            }
        }
    
        return occur;
    }
    
  • + 0 comments

    Basic solution

    int beautifulBinaryString(string b) { int result = 0; while (b.find("010")!=string::npos) { ++b[b.find("010")+2]; result++; } return result; }

  • + 0 comments
    def beautifulBinaryString(b):
        # Write your code here
        operations = 0
        count = 0
        while count < len(b) - 2:
            if b[count: count+3] == "010":
                operations += 1
                count += 3
                continue
            count+= 1
        return operations