Beautiful Binary String

  • + 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.